1

I created a custom attribute for customer entity, with options from another db_table

I want to display this field as a select item (with options from source model) in the registration page (customer_account_create)

I created all the needed files but i don't know how to get the options (created in source model) in the template file

Here is all the created/needed files:

InstallData Vendor/Module/Setup/InstallData.php

    <?php

namespace Vendor\Module\Setup;

use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Customer\Model\Customer;
use Magento\Eav\Model\Entity\Attribute\Set as AttributeSet;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

/**
 * @codeCoverageIgnore
 */
class InstallData implements InstallDataInterface
{

    /**
     * @var CustomerSetupFactory
     */
    protected $customerSetupFactory;

    /**
     * @var AttributeSetFactory
     */
    private $attributeSetFactory;

    /**
     * @param CustomerSetupFactory $customerSetupFactory
     * @param AttributeSetFactory $attributeSetFactory
     */
    public function __construct(
        CustomerSetupFactory $customerSetupFactory,
        AttributeSetFactory $attributeSetFactory
    ) {
        $this->customerSetupFactory = $customerSetupFactory;
        $this->attributeSetFactory = $attributeSetFactory;
    }


    /**
     * {@inheritdoc}
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {

        /** @var CustomerSetup $customerSetup */
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

        $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
        $attributeSetId = $customerEntity->getDefaultAttributeSetId();

        /** @var $attributeSet AttributeSet */
        $attributeSet = $this->attributeSetFactory->create();
        $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);



        $setup->startSetup();

        $customerSetup->addAttribute(Customer::ENTITY, 'testfield', [
            'type' => 'varchar',
            'label' => 'Test Field',
            'input' => 'select',
            'required' => false,
            'visible' => true,
            'system' => 0,
            'user_defined' => true,
            'visible_on_front' => true, 
            'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
            'source' => 'Vendor\Module\Model\Customer\Attribute\Source\Test'
        ]);

        $attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'testfield')
        ->addData([
            'attribute_set_id' => $attributeSetId,
            'attribute_group_id' => $attributeGroupId,
            'used_in_forms' => ['adminhtml_customer','customer_account_create','customer_account_edit','checkout_register'],
        ]);

        $attribute->save();

        $setup->endSetup();

        }
    }

Source Model Vendor/Module/Model/Customer/Attribute/Source/Test.php

<?php
namespace Vendor\Module\Model\Customer\Attribute\Source;


class Test extends \Magento\Eav\Model\Entity\Attribute\Source\Table
{
    /**
     * @return array
     */
    public function getAllOptions()
    {
        $obj = \Magento\Framework\App\ObjectManager::getInstance();
        $helper = $obj->create('Vendor\Module\Helper\Data');
        $tags = $helper->getCollection();
        foreach($tags as $tag){
            $label = $tag->getName();
            $value = $tag->getCode();
            $option[] = array('label'=>$label,'value'=>$value);
        }
        $this->_options = $option;

        return $this->_options;
    }

}

Helper Vendor/Module/Helper/Data.php

<?php

namespace Vendor\Module\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    protected $_tagsCollectionFactory;

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Vendor\Module\Model\ResourceModel\Test\CollectionFactory $tagsCollectionFactory
    ) {
        $this->_tagsCollectionFactory = $tagsCollectionFactory;
        parent::__construct($context);
    }

    public function getCollection()
    {
        $collection = $this->_tagsCollectionFactory->create();
        return $collection;
    }

}

Layout Vendor/Module/view/frontend/layout/customer_account_create.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
    <referenceContainer name="form.additional.info">
        <block class="Magento\Framework\View\Element\Template" name="additional_info_customer" template="Vendor_Module::additionalinfocustomer.phtml"/>
    </referenceContainer>
</body>
</page>

Template (Needed file) Vendor/Module/view/frontend/templates/additionalinfocustomer.phtml

<fieldset class="fieldset create account" data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>">
    <legend class="legend"><span><?php /* @escapeNotVerified */ echo __('Additional Information') ?></span></legend>

   <!-- Need select item for testField customer attribute -->
   <!-- Options from db_table (in source model)-->
   ............................................................


</fieldset>

Could any one help me how to get this select options in template ?

0
use Magento\Eav\Model\Config as EavConfig;

protected $eavConfig;


public function __construct(
    ...
    Config $eavConfig
    ....
) {
    ....
    $this->eavConfig = $eavConfig;
    ....
}

Now you can load your attribute like this,

$yourAttribute=$this->eavConfig->getAttribute('customer','YOUR_ATTRIBUTE_CODE');

if($yourAttribute->getSource()){
    $options = $yourAttribute->getSource()->getAllOptions();
}

Using ObjectManager (Not recommended)

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$yourAttribute = $objectManager->create('Magento\Eav\Model\Config')->getAttribute('customer','YOUR_ATTRIBUTE_CODE');

if($yourAttribute->getSource()){
    $options = $yourAttribute->getSource()->getAllOptions();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.