升级脚本-使用选项创建新的select属性


27

我想使用升级脚本用一些预定义的选项创建一个新的产品属性。

我有一个升级脚本在工作,所以我唯一不知道怎么做的就是添加下拉选项和属性。

我使用以下命令在模块升级脚本中添加属性:

$installer->addAttribute('catalog_product', "shirt_size", array(
    'type'       => 'int',
    'input'      => 'select',
    'label'      => 'Shirt Size',
    'sort_order' => 1000,
    'required'   => false,
    'global'     => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
));

如何添加三个选项:小型,中型和大型?

我不想使用自定义源模型。我想要正常的选择

Answers:


30

这是经典的情况,代码生成是您的朋友。停止手动创建这些脚本,并尝试使用以下免费开放源代码脚本(该脚本也已合并到该n98-magerun工具中)

例如,以下将复制示例数据的color属性

$ magento-create-setup.php color
//WARNING, non false value detected in is_used_for_price_rules.  The setup resource migration scripts may not support this (per 1.7.0.1)
<?php
if(! ($this instanceof Mage_Catalog_Model_Resource_Setup) )
{
    throw new Exception("Resource Class needs to inherit from " .
    "Mage_Catalog_Model_Resource_Setup for this to work");
}

$attr = array (
  'attribute_model' => NULL,
  'backend' => '',
  'type' => 'int',
  'table' => '',
  'frontend' => '',
  'input' => 'select',
  'label' => 'Color',
  'frontend_class' => '',
  'source' => '',
  'required' => '0',
  'user_defined' => '1',
  'default' => '',
  'unique' => '0',
  'note' => '',
  'input_renderer' => NULL,
  'global' => '1',
  'visible' => '1',
  'searchable' => '1',
  'filterable' => '1',
  'comparable' => '1',
  'visible_on_front' => '0',
  'is_html_allowed_on_front' => '0',
  'is_used_for_price_rules' => '1',
  'filterable_in_search' => '1',
  'used_in_product_listing' => '0',
  'used_for_sort_by' => '0',
  'is_configurable' => '1',
  'apply_to' => 'simple',
  'visible_in_advanced_search' => '1',
  'position' => '1',
  'wysiwyg_enabled' => '0',
  'used_for_promo_rules' => '1',
  'option' => 
  array (
    'values' => 
    array (
      0 => 'Green',
      1 => 'Silver',
      2 => 'Black',
      3 => 'Blue',
      4 => 'Red',
      5 => 'Pink',
      6 => 'Magenta',
      7 => 'Brown',
      8 => 'White',
      9 => 'Gray',
    ),
  ),
);
$this->addAttribute(Mage_Catalog_Model_Product::ENTITY, 'color', $attr);

如果您使用的是n98-magerun版本

$ n98-magerun dev:setup:script:attribute catalog_product color

使用代码生成可以使您更快地完成工作,并且随着时间的流逝,您将开始学习格式。


我们可以添加JS事件观察像onClick,并onChange在属性选项?
RT

18
$installer->addAttribute(Mage_Catalog_Model_Product::ENTITY, 'shirt_size', [
    'type'       => 'int',
    'input'      => 'select',
    'label'      => 'Shirt Size',
    'sort_order' => 1000,
    'required'   => false,
    'global'     => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
    'backend'    => 'eav/entity_attribute_backend_array',
    'option'     => [
        'values' => [
            0 => 'Small',
            1 => 'Medium',
            2 => 'Large',
        ]
    ],

]);

value数组中的每个元素代表一个选项。如果您有更多类似的信息,则可以为每个商店视图添加标签:

[
    0=>'Small',
    1=>'Small',
    2=>'Petit'
]

基本上是 store_id=>'Label for store'


6
马里乌斯,你以工作为生吗?:-)
benmarks

7
@benmarks。我确实为谋生而工作,我真的很喜欢我正在做的工作。我只是喜欢不时抽出2分钟的时间来回答问题。你要我停止回答吗?:)
Marius

1
@philwinkle。是的...每周4小时,但不是每周一次。我不想累。:)
马吕斯

1
@Dexter添加$installer = $this;为安装程序脚本的第一行。
马吕斯

1
@mujas。backend等于中的backend_modeleav_attribute table。属性可以支持前端模型(实际上是用于在后端呈现属性字段的块),源模型(用于下拉列表和多选属性。这是选项的来源)和后端模型。您可以使用设置了后端模型的类在保存属性值之前或在加载属性值之后执行操作。您可以使用它来执行其他验证或更改值。在这种特定情况下,将从表单发送的数组进行序列化。
马里斯(Marius)


0
$valStringArray = array("Nike","Addidas");
createAttribute("Brand","manufacturer",-1,-1,-1,$valStringArray);

//
// Create an attribute.
//
// For reference, see Mage_Adminhtml_Catalog_Product_AttributeController::saveAction().
//
// @return int|false
//  

function createAttribute($labelText, $attributeCode, $values = -1, $productTypes = -1, $setInfo = -1, $options = -1)
{

    $labelText = trim($labelText);
    $attributeCode = trim($attributeCode);

    if($labelText == '' || $attributeCode == '')
    {
        echo "Can't import the attribute with an empty label or code.  LABEL= [$labelText]  CODE= [$attributeCode]"."<br/>";
        return false;
    }

    if($values === -1)
        $values = array();

    if($productTypes === -1)
        $productTypes = array();

    if($setInfo !== -1 && (isset($setInfo['SetID']) == false || isset($setInfo['GroupID']) == false))
    {
        echo "Please provide both the set-ID and the group-ID of the attribute-set if you'd like to subscribe to one."."<br/>";
        return false;
    }

    echo "Creating attribute [$labelText] with code [$attributeCode]."."<br/>";

    //>>>> Build the data structure that will define the attribute. See
    //     Mage_Adminhtml_Catalog_Product_AttributeController::saveAction().

    $data = array(
                    'is_global'                     => '1',
                    'frontend_input'                => 'select',
                    'default_value_text'            => '',
                    'default_value_yesno'           => '0',
                    'default_value_date'            => '',
                    'default_value_textarea'        => '',
                    'is_unique'                     => '0',
                    'is_required'                   => '0',
                    'frontend_class'                => '',
                    'is_searchable'                 => '1',
                    'is_visible_in_advanced_search' => '1',
                    'is_comparable'                 => '1',
                    'is_used_for_promo_rules'       => '0',
                    'is_html_allowed_on_front'      => '1',
                    'is_visible_on_front'           => '0',
                    'used_in_product_listing'       => '0',
                    'used_for_sort_by'              => '0',
                    'is_configurable'               => '0',
                    'is_filterable'                 => '1',
                    'is_filterable_in_search'       => '1',
                    'backend_type'                  => 'varchar',
                    'default_value'                 => '',
                    'is_user_defined'               => '0',
                    'is_visible'                    => '1',
                    'is_used_for_price_rules'       => '0',
                    'position'                      => '0',
                    'is_wysiwyg_enabled'            => '0',
                    'backend_model'                 => '',
                    'attribute_model'               => '',
                    'backend_table'                 => '',
                    'frontend_model'                => '',
                    'source_model'                  => '',
                    'note'                          => '',
                    'frontend_input_renderer'       => '',                      
                );

    // Now, overlay the incoming values on to the defaults.
    foreach($values as $key => $newValue)
        if(isset($data[$key]) == false)
        {
            echo "Attribute feature [$key] is not valid."."<br/>";
            return false;
        }

        else
            $data[$key] = $newValue;

    // Valid product types: simple, grouped, configurable, virtual, bundle, downloadable, giftcard
    $data['apply_to']       = $productTypes;
    $data['attribute_code'] = $attributeCode;
    $data['frontend_label'] = array(
                                        0 => $labelText,
                                        1 => '',
                                        3 => '',
                                        2 => '',
                                        4 => '',
                                    );

    //<<<<

    //>>>> Build the model.

    $model = Mage::getModel('catalog/resource_eav_attribute');

    $model->addData($data);

    if($setInfo !== -1)
    {
        $model->setAttributeSetId($setInfo['SetID']);
        $model->setAttributeGroupId($setInfo['GroupID']);
    }

    $entityTypeID = Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId();
    $model->setEntityTypeId($entityTypeID);

    $model->setIsUserDefined(1);

    //<<<<

    // Save.

    try
    {
        $model->save();
    }
    catch(Exception $ex)
    {
        echo "Attribute [$labelText] could not be saved: " . $ex->getMessage()."<br/>";
        if($ex->getMessage() == "Attribute with the same code already exists."){
            if(is_array($options)){
                foreach($options as $_opt){
                    addAttributeValue($attributeCode, $_opt);
                }
            }
        }
        return false;
    }

    if(is_array($options)){
        foreach($options as $_opt){
            addAttributeValue($attributeCode, $_opt);
        }
    }

    $id = $model->getId();

    echo "Attribute [$labelText] has been saved as ID ($id).<br/>";

    // Asssign to attribute set.
    $model1 = Mage::getModel('eav/entity_setup','core_setup');
    $model1->addAttributeToSet(
        'catalog_product', 'Default', 'General', $attributeCode
    ); //Default = attribute set, General = attribute group

    // return $id;
}

function addAttributeValue($arg_attribute, $arg_value)
{
    $attribute_model        = Mage::getModel('eav/entity_attribute');

    $attribute_code         = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
    $attribute              = $attribute_model->load($attribute_code);

    if(!attributeValueExists($arg_attribute, $arg_value))
    {
        $value['option'] = array($arg_value,$arg_value);
        $result = array('value' => $value);
        $attribute->setData('option',$result);
        $attribute->save();
    }

    $attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
    $attribute_table        = $attribute_options_model->setAttribute($attribute);
    $options                = $attribute_options_model->getAllOptions(false);

    foreach($options as $option)
    {
        if ($option['label'] == $arg_value)
        {
            return $option['value'];
        }
    }
   return false;
}
function attributeValueExists($arg_attribute, $arg_value)
{
    $attribute_model        = Mage::getModel('eav/entity_attribute');
    $attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;

    $attribute_code         = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
    $attribute              = $attribute_model->load($attribute_code);

    $attribute_table        = $attribute_options_model->setAttribute($attribute);
    $options                = $attribute_options_model->getAllOptions(false);

    foreach($options as $option)
    {
        if ($option['label'] == $arg_value)
        {
            return $option['value'];
        }
    }

    return false;
}

尝试这个。我通过此代码添加了如此多的属性和属性值,您可以通过此代码将属性分配给属性集。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.