Home  >  Article  >  php教程  >  Yii2 framework study notes (4) -- the first Widget

Yii2 framework study notes (4) -- the first Widget

黄舟
黄舟Original
2016-12-30 09:51:061181browse

The biggest function of the front desk is to display pictures. After the user clicks, the pictures can be popped up and displayed enlarged.

JQuery has two plug-ins that can help us achieve our goals

Magnific-Popup(http://dimsemenov.com/plugins/magnific-popup/): Used to create pop-up windows.

Bricks(https://github.com/floo51/jquery-bricks): When multiple images exist, it will automatically help us adjust the size of the images so that they can be arranged on the same line.

Magnific-Popup can be installed through Composer. Add content under the require node of composer.json in the Yii directory

"require": {  
          ...  
         "dimsemenov/magnific-popup": "*",  
          ...  
    },

Then start the command line tool in the yii directory and run composer update .

The installed files are placed in the vendor folder. To be applied to the front page, they need to be exposed as an AssetBundle. Another benefit of using AssetBundle is that it can help us handle dependencies, and we can only use these resources where needed instead of wrapping these things in every page to increase the burden.

Create a new MangificPopupAsset.php under frontend/assets with the following content

namespace frontend\assets;  
  
use yii\web\AssetBundle;  
  
class MagnificPopupAsset extends AssetBundle  
{  
    public $sourcePath = '@vendor/dimsemenov/magnific-popup/dist';  
    public $css = [  
            'magnific-popup.css',  
    ];  
    public $js = [  
            'jquery.magnific-popup.js',  
    ];  
    public $depends = [  
            'yii\web\JqueryAsset',  
    ];  
}

The preliminary preparations are ready and you can start writing widgets.

Create new frontend/widgets/ImagePopup.php (if the folder does not exist, create a new one)

The parent class is yii\base\Widget, and you mainly need to override the init and run methods. init is used to initialize parameters, and run is used to render html code.

The specific code is as follows

namespace frontend\widgets;

use yii\base\Widget;
use yii\base\InvalidConfigException;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use yii\web\View;
use frontend\assets\MagnificPopupAsset;

class ImagePopup extends Widget {
	
	public $options;
	public $clientOptions = [];
	
	public function init() {
		if (!isset($this->options['src'])) {
			throw new InvalidConfigException("Image src must provided");
		}
		if (!isset($this->options['dest'])) {
			throw new InvalidConfigException("Popup destination must provided");
		}
		if (!isset($this->options['type'])) {
			if(isset($this->clientOptions['type'])) {
				$this->options['type'] = $this->clientOptions['type'];
			} else {
				$this->options['type'] = 'ajax';
			}
		}
		if (!isset($this->options['id'])) {
			$this->options['id'] = $this->getId();
		}
		if (!isset($this->options['wrapDiv'])) {
			$this->options['wrapDiv'] = true;
		}
		if (!isset($this->options['class'])) {
			$this->options['class'] = '';
		}
		$_options = [
			"items" => [ "src" => $this->options['dest'], ],
			"type" => $this->options['type'],
		];
		$this->clientOptions = ArrayHelper::merge($_options, $this->clientOptions);
		parent::init();
	}
	
	public function run() {
		$this->registerClientScript();
		if ($this->options['wrapDiv']) {
			$result = "
options['id'] . "' "; $result .= "class='" . $this->options['class'] . "'"; $result .= ">"; $result .= Html::img($this->options['src']); $result .= "
"; return $result; } else { return Html::img($this->options['src'], [ 'id' => $this->options['id'], 'class' => $this->options['class'], ]); } } protected function registerClientScript() { MagnificPopupAsset::register($this->view); $option = Json::encode($this->clientOptions); $script = "$('#" . $this->options['id'] . "').magnificPopup(" . $option . ")"; $this->view->registerJs($script, View::POS_READY); } }

Then you can call the control as follows

echo ImagePopup::widget([     
    "options" => [  
        "src" => "image/thumb/1.jpg",  
        "dest" => $url,  
    ]  
  ]);

The src parameter is the displayed thumbnail, and dest is what pops up after clicking. You can It is a url, called with ajax, or it can be an image address to display the image directly.

The html source code of the pop-up window is omitted.

Then reference another JQuery plug-in to help us layout the image.

This plug-in does not provide a composer installation method. Download the js file directly and place it in frontend/web/js.

Similarly, assets also need to be used as layer packaging to ensure that the js is only referenced where needed.

frontend/assets/BricksAsset.php

namespace frontend\assets;  
  
use yii\web\AssetBundle;  
  
class BricksAsset extends AssetBundle  
{  
    public $basePath = '@webroot';  
    public $baseUrl = '@web';  
    public $css = [  
    ];  
    public $js = [  
        'js/jquery-bricks.min.js',  
    ];  
    public $depends = [  
        'yii\web\JqueryAsset',  
    ];  
}

It should be noted that when we referenced resources outside the web folder before, we used sourcePath, and the yii framework will automatically copy them to the web folder for us. Down. This time the file is already in the web folder, so you need to use basePath to prevent repeated copying.

Then register the assetbundle on the home page and call the control we wrote before.

frontend/views/site/index.php

title = Yii::t('common', Yii::$app->name);
?>

[ "src" => "image/thumb/2.jpg", "dest" => $url, "wrapDiv" => false, ] ]); echo ImagePopup::widget([ "options" => [ "src" => "image/thumb/5.jpg", "dest" => $url, "wrapDiv" => false, ] ]); echo ImagePopup::widget([ "options" => [ "src" => "image/thumb/6.jpg", "dest" => $url, "wrapDiv" => false, ] ]); echo ImagePopup::widget([ "options" => [ "src" => "image/thumb/7.jpg", "dest" => $url, "wrapDiv" => false, ] ]); echo ImagePopup::widget([ "options" => [ "src" => "image/thumb/8.jpg", "dest" => $url, "wrapDiv" => false, ] ]); echo ImagePopup::widget([ "options" => [ "src" => "image/thumb/9.jpg", "dest" => $url, "wrapDiv" => false, ] ]); echo ImagePopup::widget([ "options" => [ "src" => "image/thumb/10.jpg", "dest" => $url, "wrapDiv" => false, ] ]); echo ImagePopup::widget([ "options" => [ "src" => "image/thumb/11.jpg", "dest" => $url, "wrapDiv" => false, ] ]); ?>
registerJs($script); ?>

The effect after completion and the effect after clicking to pop up are as follows.

Yii2 framework study notes (4) -- the first Widget

The above are the Yii2 framework study notes (4) - the content of the first Widget. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn