Magento2创建自定义Widget 并通过添加图片选择器插入图片
为什么80%的码农都做不了架构师?>>>
创建自定义Widget 并通过添加图片选择器插入图片
自定义widget
先在模块的etc 配置文件中创建
widget.xml
配置文件例如:在
HomeCategoryLis
t模块中创建widget
文件位置:\Rokanthemes\HomeCategoryList\etc\widget.xml
代码内容:
<widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="../../../Magento/Widget/etc/widget.xsd"><widget id="custom_homepage_category_title" class="Rokanthemes\HomeCategoryList\Block\HomeCategoryTitle"is_email_compatible="true"placeholder_image="Magento_CatalogWidget::images/products_list.png" ttl="86400"><label translate="true">Custom Homepage Category Title</label><description translate="true">Custom Homepage Category Title</description><parameters><parameter name="title" xsi:type="text" required="true" visible="true"><label translate="true">Title</label></parameter><parameter name="short_desc" xsi:type="text" required="false" visible="true"><label translate="true">Short Desc</label></parameter></parameters></widget> </widgets>
在block中创建对应的类
上面配置中
<widget>
标签中的class
值为当前widget
所对应的class
类,所以要在对应位置创建HomeCategoryTitle.php
文件位置为:
Rokanthemes\HomeCategoryList\Block\HomeCategoryTitle
代码内容示例:<?php namespace Rokanthemes\HomeCategoryList\Block; class HomeCategoryTitle extends \Magento\Catalog\Block\Product\AbstractProduct implements \Magento\Widget\Block\BlockInterface {protected $httpContext;protected $_catalogProductVisibility;protected $productCollectionFactory;protected $sqlBuilder;protected $rule;protected $conditionsHelper;protected $_categoryFactory;protected $productFactory;protected $_scopeConfig;public function __construct(\Magento\Catalog\Block\Product\Context $context,\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,\Magento\Catalog\Model\Product\Visibility $catalogProductVisibility,\Magento\Framework\App\Http\Context $httpContext,\Magento\Rule\Model\Condition\Sql\Builder $sqlBuilder,\Magento\CatalogWidget\Model\Rule $rule,\Magento\Widget\Helper\Conditions $conditionsHelper,\Magento\Catalog\Model\CategoryFactory $categoryFactory,array $data = []) {$this->productCollectionFactory = $productCollectionFactory;$this->_catalogProductVisibility = $catalogProductVisibility;$this->httpContext = $httpContext;$this->sqlBuilder = $sqlBuilder;$this->rule = $rule;$this->conditionsHelper = $conditionsHelper;$this->_categoryFactory = $categoryFactory;$this->_scopeConfig = $context->getScopeConfig();parent::__construct($context,$data);$this->_isScopePrivate = true;}/*** {@inheritdoc}*/protected function _construct(){ parent::_construct();$this->setTemplate('widget/home_category_title.phtml');}public function getTitle(){return $this->getData('title');}public function getCategoryId(){$categoryIdLink = explode('/',$this->getData('category_id'));return end($categoryIdLink);}public function getLeftBigImage(){return $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).$this->getData('left_big_image');}public function getLeftBigImageLink(){return $this->getData('left_big_image_link');}public function getBaseUrl(){return $this->_storeManager->getStore()->getBaseUrl();}} ?>
创建widget对应的template文件
在上面block创建的方法中有以下代码段:
protected function _construct(){ parent::_construct();$this->setTemplate('widget/home_category_title.phtml'); }
其实这里就是设置
widget
对应的.phtml
文件所以我们需要在Rokanthemes\HomeCategoryList\view\frontend\templates\widget\
位置创建对应的home_category_title.phtml
文件。代码内容:
<div class="rokan-product-heading rokan-featured-heading"> <h2><?php echo $block->getTitle(); ?></h2> <?php if ($block->getShortDescData()): ?><div class="short_desc"><p><?php echo $this->getShortDescData(); ?></p></div> <?php endif; ?> </div>
命令行清除缓存重新生成静态
清除缓存:
php bin/magento cache:clean
重新安装di
php bin/magento setup:di:compile
生成静态
php bin/magento setup:static-content:deploy
自定义widget中添加图片选择器插入图片
widget.xml
中添加图片选择器parameter
<parameter name="below_image" xsi:type="block" required="true" visible="true"><label translate="true">Below Image</label><description translate="true">Select Insert photo</description><block class="Rokanthemes\HomeCategoryList\Block\Adminhtml\Widget\ImageChooser"><data><item name="button" xsi:type="array"><item name="open" xsi:type="string">Choose Image...</item></item></data></block>
</parameter>
模块block
中添加ImageChooser.php
文件
文件位置:Rokanthemes\HomeCategoryList\Block\Adminhtml\Widget\
代码:
<?phpnamespace Rokanthemes\HomeCategoryList\Block\Adminhtml\Widget;use Magento\Framework\Data\Form\Element\AbstractElement as Element;
use Magento\Backend\Block\Template\Context as TemplateContext;
use Magento\Framework\Data\Form\Element\Factory as FormElementFactory;
use Magento\Backend\Block\Template;class ImageChooser extends Template
{/*** @var \Magento\Framework\Data\Form\Element\Factory*/protected $elementFactory;/*** @param TemplateContext $context* @param FormElementFactory $elementFactory* @param array $data*/public function __construct(TemplateContext $context,FormElementFactory $elementFactory,$data = []) {$this->elementFactory = $elementFactory;parent::__construct($context, $data);}/*** Prepare chooser element HTML** @param Element $element* @return Element*/public function prepareElementHtml(Element $element){$config = $this->_getData('config');$sourceUrl = $this->getUrl('cms/wysiwyg_images/index',['target_element_id' => $element->getId(), 'type' => 'file']);/** @var \Magento\Backend\Block\Widget\Button $chooser */$chooser = $this->getLayout()->createBlock('Magento\Backend\Block\Widget\Button')->setType('button')->setClass('btn-chooser')->setLabel($config['button']['open'])
// ->setOnClick( "MediabrowserUtility.openDialog( '$sourceUrl', null, null, '".$this->escapeQuote(__('Choose Image...'),true)."', (opt = new Object(), opt.closed = false, opt) )" )->setOnClick('MediabrowserUtility.openDialog(\''. $sourceUrl .'\')')->setDisabled($element->getReadonly());/** @var \Magento\Framework\Data\Form\Element\Text $input */$input = $this->elementFactory->create("text", ['data' => $element->getData()]);$input->setId($element->getId());$input->setForm($element->getForm());$input->setClass("widget-option input-text admin__control-text");if ($element->getRequired()) {$input->addClass('required-entry');}$element->setData('after_element_html', $input->getElementHtml() . $chooser->toHtml());return $element;}
}
创建拦截器对插入图片地址进行处理
因为是在widget中插入图片,默认会插入带有'{{','}}'的引用方式,会与widget的引用造成冲突从而使图片无法正常显示。所以需要在插入动作之后对图片地址进行处理
创建一个新的插件(拦截器) Rokanthemes/HomeCategoryList/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd"><type name="Magento\Widget\Model\Widget"><plugin name="insert_picture_before" type="Rokanthemes\HomeCategoryList\Model\Widget" sortOrder="1" disabled="false"/></type>
</config>
然后创建拦截器逻辑,需要使用before方法,这样就可以改变传递给\Magento\Widget\Model\Widget
方法getWidgetDeclaration
的参数,getWidgetDeclaration
。
文件位置:Rokanthemes\HomeCategoryList\Model\
文件名:Widget.php
代码内容:
<?php
/*** Created by PhpStorm.* User: Hankin.Peng* Date: 2018/7/20* Time: 16:03*/
namespace Rokanthemes\HomeCategoryList\Model;use \Magento\Widget\Model\Widget as BaseWidget;class Widget
{public function beforeGetWidgetDeclaration(BaseWidget $subject, $type, $params = [], $asIs = true){// I rather do a check for a specific parameters$str='Rokanthemes\HomeCategoryList\Block\HomeCategory';$pictureStr='Picture';if(strstr($type,$str) && stristr($type,$pictureStr)) {foreach ($params as $paramKey => $value) {$url = $params[$paramKey];if (strpos($url, '/directive/___directive/') !== false) {$parts = explode('/', $url);$key = array_search("___directive", $parts);if ($key !== false) {$url = $parts[$key + 1];$url = base64_decode(strtr($url, '-_,', '+/='));$parts = explode('"', $url);$key = array_search("{{media url=", $parts);$url = $parts[$key + 1];$params[$paramKey] = $url;}}}}return array($type, $params, $asIs);}
}
转载于:https://my.oschina.net/hleva/blog/2246691
Magento2创建自定义Widget 并通过添加图片选择器插入图片相关推荐
- CSS学习记录3.2/设置标签的背景颜色/控制背景图片的平铺方式/控制背景图片的位置/背景图片关联方式/背景图片和插入图片的区别/捕鱼达人背景练习/精灵图
设置标签的背景颜色: CSS中的background-color:属性,就是专门用来设置标签.bc+table 设置背景图片: CSS中的background-image: url( );的属性就是设 ...
- 背景图片和插入图片的区别
背景图片和插入图片的区别: 背景图片有定位属性, 所以可以很方便的控制图片的位置 插入图片没有定位属性, 所以控制图片的位置不太方便 转自:https://blog.csdn.net/weixin_5 ...
- html的div插入图片,html插入图片示例(html添加图片)
原标题:html插入图片示例(html添加图片) 在html插入图片 让图片显示需要HTML标签来实现,使用img标签即可实现. 一.html图片标签语法 复制代码 代码如下: img介绍: src ...
- Android 图片选择器和图片裁剪库
前言:现在大部分的App都支持上传图片和裁剪图片的功能,比如设置用户头像.聊天发送图片.发表动态.论坛帖子等.上传图片需要先从选择手机中选择要上传的图片,所以图片选择器在App中是很常见的组件,一般的 ...
- 手机怎么在PDF中插入图片?插入图片方法教程
如何使用手机在PDF文件中插入图片呢?PDF文件大家在办公中经常使用,使用的过程中难免会有编辑文件的需求.很多时候我们会需要在文件中插入或添加图片,来丰富内容多样性,如果在需要编辑文件的时候,身边有电 ...
- iOS开发 图片选择器、图片多选功能的实现
版权声明:本文为博主原创文章,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接. Photos.framework是iOS8后苹果推出的一套替代AssetsLibrary.f ...
- Android 图片选择器、图片剪切,文件选择器
单张图片选择 1.在build.gradle中dependencies下添加依赖 compile 'com.github.lovetuzitong:MultiImageSelector:1.2' 2. ...
- 知乎图片选择器 Matisse 图片出错问题分析
配置Matisse 需要在清单文件中 添加: <providerandroid:name="android.support.v4.content.FileProvider"a ...
- excel poi 加背景图_java 在Excel中插入图片 POI实现
一.POI简介 Jakarta POI 是apache的子项目,目标是处理ole2对象.它提供了一组操纵Windows文档的Java API 目前比较成熟的是HSSF接口,处理MS Excel(97- ...
最新文章
- SAP SD 以PDF格式显示BILLING的输出格式
- 为什么在中国“公有云”落地那么难?
- 升级MAC OX上的Python到3.4
- 光电转换器有什么作用?光纤收发器如何保养?
- USACO section1.3 Barn Repair 修理牛棚(贪心)
- edge浏览器如何把网页放到桌面_电脑如何添加便签,便签怎么放到桌面上
- 快速排序算法_大佬的快速排序算法,果然不一样
- 安卓dj专业打碟机软件_学DJ打碟必备设备
- win10硬盘分区怎么分
- 免费ftp上传工具,三款免费的ftp上传工具
- android m3u8 合并,M3u8合并APP
- 微商卖货怎么引流?微商怎么找客源?
- 最唯美的10首中国情诗
- Nature证实:学术界刮起离职潮!大批学者涌向工业界,互助文档日均20个学者离职...
- 蓝牙协议栈模组在linux ubuntu 跑蓝牙协议栈 --传统蓝牙搜索演示以及实现原理
- 推荐一个GitHub上牛b的Java学习项目,已整理成了文档版本
- 红帽linux系统下载6,红帽linux系统下载|红帽linux(RHEL)下载 v6.5 beta 官方版_小皮网...
- ArcGIS官方帮助文档和教程整理
- 这 7 门 编程语言最适合新手学习
- 计算机毕业设计java+springboot+vue学生宿舍管理系统
热门文章
- 学习vue3系列watch
- dell2100服务器组装,戴尔poweredge r730服务器配置及系统安装详解教程
- python找出只出现一次的数字_【LeetCode 136】只出现一次的数字(Python)
- HTML课程表应用,可在PC和Android运行
- java中的集合_Java 集合介绍,常用集合类
- ef mysql 读写分离_基于 EntityFramework 的数据库主从读写分离服务插件
- 两个按钮间设置空格(间距)
- js日期格式化写法及获取当前日期年月日、上一月
- 宝宝安全座椅什么牌子好?[自己参考]
- VB中用API实现文件拖放