¿Cómo agregar mediante programación valores de opciones de atributos en el script de actualización de datos?


10

Quiero agregar mediante programación nuevos valores de opciones de producto en un script de actualización de datos de mi módulo. ¿Cómo puedo hacer esto?

Respuestas:


12

Agregue el siguiente código en su archivo de script de actualización

<?php   
$installer = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();

$attributeCode = 'manufacturer';
$attribute = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product', $attributeCode);

if ($attribute->getId() && $attribute->getFrontendInput()=='select') {
    $option['attribute_id'] = $attribute->getId();
    $option['value']        =  array('Red','Black', 'Yellow');
    $installer->addAttributeOption($option);
}

//OR
/*
if($attribute->getId() && $attribute->getFrontendInput()=='select') {
    $option['attribute_id'] = $attribute->getId();
    $option['value']['r'][0] = 'Red';
    $option['value']['b'][1] = 'Black';
    $option['value']['y'][2] = 'Yellow';
    $installer->addAttributeOption($option);
}*/

$installer->endSetup();

Verifique el código del valor de la opción duplicada:

<?php   
$installer = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();

$attributeCode = 'manufacturer';
$attribute = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product', $attributeCode);

 if($attribute->getId() && $attribute->getFrontendInput()=='select') {
    $newOptions =  array('Red','Black', 'Yellow');
    $exitOptions =  array();
    $options = Mage::getModel('eav/entity_attribute_source_table')
                        ->setAttribute($attribute)
                        ->getAllOptions(false);
    foreach ($options as $option) {
        if (in_array($option['label'], $newOptions)) {
            array_push($exitOptions, $option['label']);
        }else {

        }
    }
    $insertOptions = array_diff($newOptions, $exitOptions);
    if(!empty($insertOptions)) {
        $option['attribute_id'] = $attribute->getId();
        $option['value']        =  $insertOptions;  
        $installer->addAttributeOption($option);
    }            
}

$installer->endSetup();

1
¿Cuál es el significado de los índices 'r', 'b', 'y'en $option['value']['r'][0] = 'Red';?
Anton Belonovich

1
Eso crea una opción desplegable rota aquí, en Magento CE 1.9. La tabla eav_attribute_optionobtiene una nueva fila, pero sin una fila correspondiente eav_attribute_option_value. Debe ser algo con la $optionestructura de matriz.
Anse

¿Me pueden ayudar a verificar el valor del atributo si ese valor ya está disponible? Entonces, el valor duplicado no se inserta en el atributo
Purushotam Sharma

@Purushotam Sharma: Actualizaciones y por favor verifique y hágame saber si está funcionando o no porque no estoy probando el código.
Abdul

hola @ Abdul! no agrega opción mientras ejecuta este script
SagarPPanchal

12

prueba esto,

para un solo valor: -

$arg_attribute = 'color';
$arg_value = 'red';

$attr_model = Mage::getModel('catalog/resource_eav_attribute');
$attr = $attr_model->loadByCode('catalog_product', $arg_attribute);
$attr_id = $attr->getAttributeId();

$option['attribute_id'] = $attr_id;
$option['value']['any_option_name'][0] = $arg_value;

$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttributeOption($option);

para valores múltiples: -

$arg_attribute = 'color';
$key_data = array('red','black','orange');
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$attr_model = Mage::getModel('catalog/resource_eav_attribute');
$attr = $attr_model->loadByCode('catalog_product', $arg_attribute);
foreach($key_data as $key_value)
{   
    $option = array();
    $arg_value = trim($key_value);
    $attr_id = $attr->getAttributeId();
    $option['attribute_id'] = $attr_id;
    $option['value']['any_option_name'][0] = $arg_value;
    $setup->addAttributeOption($option);
}

'any_option_name' sería un color_name (ej: rojo) arg_value sería su entero optionId afaik.

Lo que también necesitaría ser adquirido primero, es cuál es la siguiente opción ID no utilizada. Para ser utilizado para esta nueva opción de atributo.


6

Por ejemplo, desea agregar Menvalor a la genderopción.

Primero debe crear su script de actualización en el directorio del módulo, por ejemplo app/code/local/MyCompany/MyModule/data/mymodule_setup/data-upgrade-0.1.0-0.1.1.php.

Luego llénalo con un código como este:

<?php

$this->startSetup();

$genderAttribute = Mage::getModel('eav/entity_attribute')
    ->loadByCode('catalog_product', 'gender'); // 'gender' is your attribute code

$this->addAttributeOption([
    'attribute_id' => $genderAttribute->getId(),
    'value' => [[0 => 'Men', 1 => 'Men', 10 => 'Men']] // array indexes are store IDs
]);

$this->endSetup();

2

El siguiente código agrega opciones de atributos programáticamente magento 1.

Consulte la explicación detallada sobre cómo leer CSV y comparar con las opciones de atributos existentes https://www.pearlbells.co.uk/add-attribute-options-magento-scripts/

function createAttribute( $options , $attributeCode) {
$option = array('attribute_id' => 
Mage::getModel('eav/entity_attribute')->getIdByCode(
     Mage_Catalog_Model_Product::ENTITY, 
     $attributeCode
    )
);

for ($i = 0; $i < count($options); $i++) {

    $option['value']['option'.$i][0] = $options[ $i ]; // Store View
    $option['value']['option'.$i][1] = $options[ $i ]; // Default store view
    $option['order']['option'.$i] = $i; // Sort Order
    echo 'Insert new option : '.$options[ $i ].PHP_EOL;

}

$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttributeOption($option);
}
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.