Magento2如何在admin cms中添加图像上传器字段

时间:2017-06-02 05:38:51

标签: image content-management-system admin magento2

Magento2 - 如何在Admin cms页面中添加image up-loader字段。

在以下路径中添加了代码 应用\代码\命名空间\ MODULENAME \视图\ adminhtml \ ui_component \ cms_page_form.xml

    <field name="page_image">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="dataType" xsi:type="string">string</item>
                <item name="source" xsi:type="string">page</item>
                <item name="label" xsi:type="string" translate="true">Page Image</item>
                <item name="visible" xsi:type="boolean">true</item>
                <item name="formElement" xsi:type="string">fileUploader</item>
                <item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
                <item name="previewTmpl" xsi:type="string">Magento_Catalog/image-preview</item>
                <item name="required" xsi:type="boolean">false</item>
                <item name="sortOrder" xsi:type="number">40</item>
                <item name="uploaderConfig" xsi:type="array">
                    <item name="url" xsi:type="url" path="catalog/category_image/upload"/>
                </item>
            </item>
        </argument>
    </field>

在cms_page表中创建了page_image字段。我上传图片时会显示图像预览。但是如何保存图像(数据库和服务器)以及如何在编辑模式下显示上传的图像。

1 个答案:

答案 0 :(得分:2)

首先,您必须创建自己的模块以覆盖cms页面的保存操作和dataProvider。 如果您不知道如何创建模块请参阅此链接http://inchoo.net/magento-2/how-to-create-a-basic-module-in-magento-2/

创建模块后,请按照以下步骤操作:

步骤1.在cms_page表中添加自定义图像列

在[Vendor] [Module] \ Setup下创建InstallScema.php。您的文件位置将是[Vendor] [Module] \ Setup \ InstallSchema.php     

namespace [Vendor]\[Module]\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Ddl\Table;

class InstallSchema implements InstallSchemaInterface
{
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();
        $connection = $installer->getConnection();

        $connection->addColumn('cms_page','your_image_field_name',['type' =>\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,'comment' => 'Your Image Field Name']);
        $installer->endSetup();
    }
}

如果您的模块已经激活,请从setup_module表中删除您的模块。

创建InstallSchema.php后,打开终端并按以下命令。它会将列添加到数据库表并清除缓存。

php bin/magento cache:flush;
php bin/magento setup:upgrade;
php bin/magento setup:di:compile;
rm -rf var/generation/* var/di/* var/cache/* var/page_cache/* ;
rm -rf pub/static/frontend pub/static/_requirejs pub/static/adminhtml ;

步骤2.添加图片字段

在[Vendor] / [Mdoule] / View / adminhtml / ui_component下创建cms_page_form.xml。您的文件位置将是[Vendor] / [Mdoule] /View/adminhtml/ui_component/cms_page_form.xml。 添加以下代码。

<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="content">
        <field name="your_image_field_name">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="dataType" xsi:type="string">string</item>
                    <item name="source" xsi:type="string">category</item>
                    <item name="label" xsi:type="string" translate="true">Your image field Name</item>
                    <item name="visible" xsi:type="boolean">true</item>
                    <item name="formElement" xsi:type="string">fileUploader</item>
                    <item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
                    <item name="required" xsi:type="boolean">false</item>
                    <item name="uploaderConfig" xsi:type="array">
                        <item name="url" xsi:type="url" path="[module]/cms_heroimage/upload"/>
                    </item>
                </item>
            </argument>
        </field>
    </fieldset>
</form>

这将在内容标签下生成字段。

步骤3.为上传操作创建控制器。

在[Vendor] / [Mdoule] / Controller / Adminhtml / Cms / Heroimage上创建Upload.php。您的文件位置将是[Vendor] / [Mdoule] /Controller/Adminhtml/Cms/Heroimage/Upload.php。

添加以下代码。     

use Magento\Framework\Controller\ResultFactory;

class Upload extends \Magento\Backend\App\Action
{
    /**
     * Image uploader
     *
     * @var \[Namespace]\[Module]\Model\ImageUploader
     */
    protected $imageUploader;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Magento\Catalog\Model\ImageUploader $imageUploader
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Catalog\Model\ImageUploader $imageUploader
    ) {
        parent::__construct($context);
        $this->imageUploader = $imageUploader;
    }


    /**
     * Upload file controller action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        try {
            $result = $this->imageUploader->saveFileToTmpDir('your_image_field_name');

            $result['cookie'] = [
                'name' => $this->_getSession()->getName(),
                'value' => $this->_getSession()->getSessionId(),
                'lifetime' => $this->_getSession()->getCookieLifetime(),
                'path' => $this->_getSession()->getCookiePath(),
                'domain' => $this->_getSession()->getCookieDomain(),
            ];
        } catch (\Exception $e) {
            $result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
        }
        return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
    }
}
?>

步骤4.覆盖保存操作。

在[Vendor] [Module] \ etc \ adminhtml下创建di.xml。您的文件位置将是[Vendor] [Module] \ etc \ adminhtml \ di.xml  添加以下行以覆盖cms页面的Save Action和DataProvider。

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Cms\Controller\Adminhtml\Page\Save" type="[Vendor]\[Module]\Controller\Adminhtml\Cms\Page\Save" />
    <preference for="Magento\Cms\Model\Page\DataProvider" type="[Vendor]\[Module]\Model\Cms\Page\DataProvider" />
</config>

步骤5.创建Save.php文件。  在[Vendor] [Module] \ Controller \ Adminhtml \ Cms \ Page下创建Save.php文件。您的文件位置将是[Vendor] [Module] \ Controller \ Adminhtml \ Cms \ Page \ Save.php。  添加以下代码。     

use Magento\Backend\App\Action;
use Magento\Cms\Model\Page;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\Exception\LocalizedException;

class Save extends \Magento\Cms\Controller\Adminhtml\Page\Save
{
    /**
     * Authorization level of a basic admin session
     *
     * @see _isAllowed()
     */
    const ADMIN_RESOURCE = 'Magento_Cms::save';

    /**
     * @var PostDataProcessor
     */
    protected $dataProcessor;

    /**
     * @var DataPersistorInterface
     */
    protected $dataPersistor;


    /**
     * Save action
     *
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $data = $this->getRequest()->getPostValue();


        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        if ($data) {
            $data = $this->dataProcessor->filter($data);
            if (isset($data['is_active']) && $data['is_active'] === 'true') {
                $data['is_active'] = Page::STATUS_ENABLED;
            }
            if (empty($data['page_id'])) {
                $data['page_id'] = null;
            }

            /** @var \Magento\Cms\Model\Page $model */
            $model = $this->_objectManager->create('Magento\Cms\Model\Page');

            $id = $this->getRequest()->getParam('page_id');
            if ($id) {
                $model->load($id);
            }

            // Add custom image field to data
            if(isset($data['your_image_field_name']) && is_array($data['your_image_field_name'])){
                $data['your_image_field_name']=$data['your_image_field_name'][0]['name'];
            }


            $model->setData($data);

            $this->_eventManager->dispatch(
                'cms_page_prepare_save',
                ['page' => $model, 'request' => $this->getRequest()]
            );

            if (!$this->dataProcessor->validate($data)) {
                return $resultRedirect->setPath('*/*/edit', ['page_id' => $model->getId(), '_current' => true]);
            }

            try {
                $model->save();
                $this->messageManager->addSuccess(__('You saved the page.'));
                $this->dataPersistor->clear('cms_page');
                if ($this->getRequest()->getParam('back')) {
                    return $resultRedirect->setPath('*/*/edit', ['page_id' => $model->getId(), '_current' => true]);
                }
                return $resultRedirect->setPath('*/*/');
            } catch (LocalizedException $e) {
                $this->messageManager->addError($e->getMessage());
            } catch (\Exception $e) {
                $this->messageManager->addException($e, __('Something went wrong while saving the page.'));
            }

            $this->dataPersistor->set('cms_page', $data);
            return $resultRedirect->setPath('*/*/edit', ['page_id' => $this->getRequest()->getParam('page_id')]);
        }
        return $resultRedirect->setPath('*/*/');
    }
}
?>

步骤6.创建DataProvider.php

在[Vendor] \ Module \ Model \ Cms \ Page下创建DataProvider.php。您的文件位置将是[供应商] \ Module \ Model \ Cms \ Page \ DataProvider.php

<?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace [Vendor]\Module\Model\Cms\Page;

use Magento\Cms\Model\ResourceModel\Page\CollectionFactory;
use Magento\Framework\App\Request\DataPersistorInterface;

/**
 * Class DataProvider
 */
class DataProvider extends \Magento\Cms\Model\Page\DataProvider
{

    /**
     * Get data
     *
     * @return array
     */
    public function getData()
    {
        if (isset($this->loadedData)) {
            return $this->loadedData;
        }
        $items = $this->collection->getItems();
        /** @var $page \Magento\Cms\Model\Page */
        foreach ($items as $page) {
            $this->loadedData[$page->getId()] = $page->getData();
        }

        $data = $this->dataPersistor->get('cms_page');


        if (!empty($data)) {
            $page = $this->collection->getNewEmptyItem();

            $page->setData($data);
            $this->loadedData[$page->getId()] = $page->getData();
            $this->dataPersistor->clear('cms_page');
        }
        /* For Modify  You custom image field data */
        if(!empty($this->loadedData[$page->getId()]['your_image_field_name'])){
            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');
            $currentStore = $storeManager->getStore();
            $media_url=$currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

            $image_name=$this->loadedData[$page->getId()]['your_image_field_name'];
            unset($this->loadedData[$page->getId()]['your_image_field_name']);
            $this->loadedData[$page->getId()]['your_image_field_name'][0]['name']=$image_name;
            $this->loadedData[$page->getId()]['your_image_field_name'][0]['url']=$media_url."cms/hero/tmp/".$image_name;
        }
        return $this->loadedData;
    }
}

注意。请替换&#34; your_image_field_name&#34;使用您的字段名称。