Thursday, December 13, 2012

How to use dynamic value in a dropdown attribute in magento


>> Here I'll show you how to use dynamic value in a dropdown product attribute. Suppose you need to store Customer Id with a product, then you've to list all customers when you creating a product.

    => First create an attribute of select type and don't need to put the option value there.



    => Now you just need to change the Source Model of this attribute. You can also do it by code. But I'm showing you the easiest way. Go to your phpMyadmin database, find the table "eav_attribute". Search the attribute that you've created. Here I've changed the source model to "vendor/product_attribute_unit". You can use your own.



     I've used a module named "vendor" and a page within app/code/local/JR/Vendor/Model/Product/Attribute/Unit.php .
    Now this the model code.
  
    <?php
    class JR_Vendor_Model_Product_Attribute_Unit extends Mage_Eav_Model_Entity_Attribute_Source_Abstract
    {
      public function getAllOptions()
      {
        $model = Mage::getModel('customer/customer');
        $collection = $model->getCollection();
        $customerArr = array();
        $customerArr[] = array('value' => '0','label' => 'Admin');
        foreach($collection as $customer)
        {
            $customer = $model->load($customer->getId());
            $customerArr[] = array(
                           'value' => $customer->getId(),
                           'label' => $customer->getEmail(),
                            );
        }
        if (!$this->_options) {
            $this->_options = $customerArr;
        }
        return $this->_options;
      }
    }
    ?>
  
    Now you're ready to use your customer to assign in a product.


No comments:

Post a Comment