简体   繁体   中英

Magento 2 add custom image attribute to customer profile and show thumbnail

Magento 2 newbie here. I have built an extension that adds to custom attribute to the customer object. The attributes are in the database and show up on the forms. My problem is with the image attribute that I called "photo_id". What is the right way of actually uploading, saving the image, showing a thumbnail that expands to full image when clicked? see image below 在此处输入图片说明

Here is my installData.php

namespace Lemon\Veripass\Setup;

use Magento\Customer\Model\Customer;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements \Magento\Framework\Setup\InstallDataInterface
{
private $eavSetupFactory;

private $eavConfig;

private $attributeResource;

public function __construct(
    \Magento\Eav\Setup\EavSetupFactory $eavSetupFactory,
    \Magento\Eav\Model\Config $eavConfig,
    \Magento\Customer\Model\ResourceModel\Attribute $attributeResource
) {
    $this->eavSetupFactory = $eavSetupFactory;
    $this->eavConfig = $eavConfig;
    $this->attributeResource = $attributeResource;
}

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
    $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
    $eavSetup->addAttribute(
        \Magento\Customer\Model\Customer::ENTITY,
        'is_verified',
        [
            'type'         => 'int',
            'label'        => 'Verified',
            'input'        => 'boolean',
            'required'     => false,
            'visible'      => true,
            'user_defined' => true,
            'position'     => 999,
            'system'       => 0,
        ]
    );
    $verifiedAttribute = $this->eavConfig->getAttribute(Customer::ENTITY, 'is_verified');

    // more used_in_forms ['adminhtml_checkout','adminhtml_customer','adminhtml_customer_address','customer_account_edit','customer_address_edit','customer_register_address']
    $verifiedAttribute->setData(
        'used_in_forms',
        ['adminhtml_customer']

    );
    $verifiedAttribute->save();

    $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

    $eavSetup->addAttribute(Customer::ENTITY, 'photo_id', [
        'type' => 'varchar',
        'label' => 'Photo ID',
        'input' => 'image',
        'required' => false,
        'visible' => true,
        'user_defined' => true,
        'sort_order' => 1000,
        'position' => 1000,
        'system' => 0,
    ]);

    $attribute = $this->eavConfig->getAttribute(Customer::ENTITY, 'photo_id');
    $attribute->setData('used_in_forms', ['adminhtml_customer','customer_account_edit']);
    $this->attributeResource->save($attribute);
}
}

my customer_form.xml

    <?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="customer">
        <field name="is_verified" formElement="checkbox">
            <settings>
                <visible>true</visible>
            </settings>
        </field>
        <field name="photo_id" formElement="image">
            <settings>
                <visible>true</visible>
            </settings>
        </field>
    </fieldset>
</form>

You can using this code like sample. customer_form.xml

<field name="photo_image" sortOrder="40" formElement="fileUploader">
   <argument name="data" xsi:type="array">
      <item name="config" xsi:type="array">
         <item name="source" xsi:type="string">customer</item>
       </item>
    </argument>
    <settings>
         <elementTmpl>ui/form/element/uploader/uploader</elementTmpl>
         <dataType>string</dataType>
         <label translate="true">Photo Image</label>
         <visible>true</visible>
         <required>true</required>
    </settings>
    <formElements>
        <fileUploader>
            <settings>
              <required>false</required>
              <uploaderConfig>
                  <param xsi:type="url" name="url" path="your_module_router/media/upload"/>
              </uploaderConfig>
              <previewTmpl>Magento_Catalog/image-preview</previewTmpl>
            </settings>
      </fileUploader>
    </formElements>
 </field>

Namspace_Module/Controller/Adminhtml/Media/Upload.php

/**
 * Class Upload
 */
class Upload extends \Magento\Backend\App\Action
{
    /**
     * Image uploader
     *
     * @var \Magento\Catalog\Model\ImageUploader
     */
    protected $imageUploader;

    /**
     * Upload constructor.
     *
     * @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;
    }

    /**
     * Check admin permissions for this controller
     *
     * @return boolean
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Mageaddons_Customs::customs');
    }

    /**
     * Upload file controller action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $imageId = $this->_request->getParam('param_name', 'image');

        try {
            $result = $this->imageUploader->saveFileToTmpDir($imageId);

            $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);
    }
}

Note: This code sample help you add so if want this code working you must modifier for right with your module

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM