1

I want to create a new attribute product with dynamic options that comes from custom tables then i want to edit my product and make it configurable according to this attribute how to proceed thanks in advance updated question

`<?php


 namespace Mdweb\ConfigAttribute\Model\Config\Source;

 use Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory;
 use Magento\Framework\DB\Ddl\Table;


 class Options extends 
 \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
 {
/**
 * @var OptionFactory
 */
protected $optionFactory;
protected $registry;
protected $prixchoix;
protected $colchoix;
/**
 * @var \BO\Choix\Model\Choix
 */
protected $_choice;


/**
 * @param OptionFactory $optionFactory
 */
public function __construct(OptionFactory $optionFactory, \Magento\Framework\Registry $registry,
                            \BO\Prix\Model\Prix $choixprix,
                            \BO\Choix\Model\Choix $choix)
{
    //you can use this if you want to prepare options dynamically

    $this->optionFactory = $optionFactory;
    $this->registry = $registry;
    $this->prixchoix = $choixprix;
    $this->_choice = $choix;
}

/**
 * Get all options
 *
 * @return array
 */
public function toOptionArray()
{

    $_product = $this->registry->registry('current_product');

    $_sku = $_product->getSku();
    if (isset($_sku)) {

        $var1 = substr($_sku, 0, 1);


        $var2 = substr($_sku, 1, 2);

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
        $connection = $resource->getConnection();
        $tableName = $resource->getTableName('table_prix');


        $fields = array('prix_unitaire');


        $sql = $connection->select()
            ->from($tableName, $fields)
            ->where('code_famille' . '=?', $var1)
            ->where('code_nom_commercial' . '=?', $var2)
            ->join('table_choix',
                'table_choix.choix_id = table_prix.code_choix',
                [
                    'designation_choix'
                ]);

        $result = $connection->fetchAll($sql);

        if ($result) {
            $i = 0;
            foreach ($result as $elt) {
                $this->_options[$i] = ['label' => " Choix" . $elt['designation_choix'] . "-" . $elt['prix_unitaire'] . "£", 'value' => " Choix" . $elt['designation_choix'] . "-" . $elt['prix_unitaire'] . "£"];
                $i++;
            }


        }





    }
    else {
        $this->_options = [['label' => __('No'), 'value' => '0'], ['label' => __('Yes'), 'value' => '1'], ['label' => __('Other'), 'value' => '2']];
    }
    return $this->_options;
}

public function getAllOptions()
{
    return $this->toOptionArray();
}
/**
 * Get a text for option value
 *
 * @param string|integer $value
 * @return string|bool
 */
public function getOptionText($value)
{
    foreach ($this->getAllOptions() as $option) {
        if ($option['value'] == $value) {
            return $option['label'];
        }
    }
    return false;
}
}`

and here is my installData

<?php

 namespace Mdweb\ConfigAttribute\Setup;

 use Magento\Eav\Setup\EavSetup;
 use Magento\Eav\Setup\EavSetupFactory /* For Attribute create  */;
 use Magento\Framework\Setup\InstallDataInterface;
 use Magento\Framework\Setup\ModuleContextInterface;
 use Magento\Framework\Setup\ModuleDataSetupInterface;

 /**
 * @codeCoverageIgnore
 */
 class InstallData implements InstallDataInterface
 {
/**
 * EAV setup factory
 *
 * @var EavSetupFactory
 */
private $eavSetupFactory;
/**
 * Init
 *
 * @param EavSetupFactory $eavSetupFactory
 */
public function __construct(EavSetupFactory $eavSetupFactory)
{
    $this->eavSetupFactory = $eavSetupFactory;

}

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{

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

    $eavSetup->removeAttribute(\Magento\Catalog\Model\Product::ENTITY,'choix_prix_product');
    $eavSetup->addAttribute(
        \Magento\Catalog\Model\Product::ENTITY,
        'choix_prix_product',/* Custom Attribute Code */
        [
            'type' => 'text',/* Data type in which formate your value save in database*/
            'backend' => '',
            'frontend' => '',
            'label' => 'Choix-Prix de vente', /* lablel of your attribute*/
            'input' => 'select',
            'class' => '',
            'source' => 'Mdweb\ConfigAttribute\Model\Config\Source\Options',
            /* Source of your select type custom attribute options*/
            'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
            /*Scope of your attribute */
            'visible' => true,
            'required' => false,
            'user_defined' => true,
            'default' => '',
            'searchable' => false,
            'filterable' => false,
            'comparable' => false,
            'visible_on_front' => false,
            'used_in_product_listing' => false,
            'unique' => false,
            'option' => [ // temporary
                'values' => [
                ],
            ],
        ]
    );
}
}

i can see the options of the attribute for existing product and for the new i can see static attribute but when i access stores->attribute enter image description here

so i can't make my product config according to this attribute

1

You can create options for select element while creating the attribute.

Let's take an example:

app/code/Namespace/Modulename/Setup/InstallData.php

<?php
namespace Namespace\Modulename\Setup;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;

class InstallData implements InstallDataInterface
{
    /**
     * EAV setup factory
     *
     * @var EavSetupFactory
     */
    private $eavSetupFactory;

    /**
     * Init
     *
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

        /**
         * Add attributes to the eav_attribute
         */
        $eavSetup->removeAttribute(\Magento\Catalog\Model\Product::ENTITY, 'product_select_attribute');
        $eavSetup->removeAttribute(\Magento\Catalog\Model\Product::ENTITY, 'product_custom_attribute');

        $statusOptions = 'Namespace\Modulename\Model\Config\Source\StatusOptions';
        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'product_select_attribute',
            [
                'group' => 'Custom Product Attribute',
                'type' => 'int',
                'backend' => '',
                'frontend' => '',
                'label' => 'Product Status',
                'input' => 'select',
                'class' => '',
                'source' => $statusOptions,
                'global' => ScopedAttributeInterface::SCOPE_GLOBAL,
                'visible' => true,
                'required' => false,
                'user_defined' => false,
                'default' => '',
                'searchable' => false,
                'filterable' => false,
                'comparable' => false,
                'is_used_in_grid' => true,
                'visible_on_front' => false,
                'used_in_product_listing' => true,
                'unique' => false
            ]
        );
    }
}

In above code i used 'source' => $statusOptions, it is defind select option dynamically.

You need to create Model file for define our custom option of select box, $statusOptions = ‘Namespace\Modulename\Model\Config\Source\StatusOptions’;

Create StatusOptions.php file under Model and define our enable and disable option value. (Use below code for static value)

app/code/Namespace/Modulename/Model/Config/Source/StatusOptions.php

<?php
namespace Namespace\Modulename\Model\Config\Source;

use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource;

class StatusOptions extends AbstractSource
{
    /**
     * Get all options
     *
     * @return array
     */
    public function getAllOptions()
    {
        if (null === $this->_options) {
            $this->_options=[
                                ['label' => __('Enable'), 'value' => 1],
                                ['label' => __('Disable'), 'value' => 0]
                            ];
        }
        return $this->_options;
    }
}

(Use below code for dynamic value)

Change below function code for dynamic data

public function getAllOptions()
{
    $collection = $this->CollectionFactory->create();
    foreach ($collection as $item) {
        $this->_options[] = [
                'label' => __($item['title']),
                'value' => $item['id'],
            ];
    }

    return $this->_options;
}

Run below command :

php bin/magento setup:upgrade

php bin/magento cache:flush

php bin/magento indexer:reindex

I hope it helps!

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.