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:061319browse

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 = "<div id=&#39;" . $this->options[&#39;id&#39;] . "&#39; ";
			$result .= "class=&#39;" . $this->options[&#39;class&#39;] . "&#39;";
			$result .= ">";
			$result .= Html::img($this->options[&#39;src&#39;]);
			$result .= "</div>";
			return $result;
		} else {
 			return Html::img($this->options[&#39;src&#39;], [
 					&#39;id&#39; => $this->options[&#39;id&#39;],
 					&#39;class&#39; => $this->options[&#39;class&#39;],				
 			]);
		}
	}
	
	protected function registerClientScript() {
		MagnificPopupAsset::register($this->view);
		$option = Json::encode($this->clientOptions);
		$script = "$(&#39;#" . $this->options[&#39;id&#39;] . "&#39;).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 = &#39;@webroot&#39;;  
    public $baseUrl = &#39;@web&#39;;  
    public $css = [  
    ];  
    public $js = [  
        &#39;js/jquery-bricks.min.js&#39;,  
    ];  
    public $depends = [  
        &#39;yii\web\JqueryAsset&#39;,  
    ];  
}

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

<?php

/* @var $this yii\web\View */
use frontend\widgets\ImagePopup;
use yii\helpers\Url;
use frontend\assets\BricksAsset;
use frontend\assets\MasonryAsset;

BricksAsset::register($this);
$this->title = Yii::t(&#39;common&#39;, Yii::$app->name);
?>

<div id="container" style="font-size:0px;">

<?php
  $url = Url::to([&#39;ajax/image-popup&#39;]);
  echo ImagePopup::widget([	
	"options" => [
		"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,
  		]
  ]);
  ?>
</div>

<?php 
$script ="$(&#39;#container&#39;).bricks();";
$script .= "$(window).resize(function() {
  $(&#39;#container&#39;).data(&#39;bricks&#39;).layout();
});";
$this->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 (www.php.cn)!


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