Posting in the Magento forums has been disabled pending the implementation of a new and improved forum solution which should better serve the community.

For new questions please post at magento.stackexchange.com, the community-run support site for the Magento community. We will be providing updates on the new forum solution soon. For questions or concerns please email community@magento.com.

Magento Forum

Adding entries to a custom attribute dropdown ( link custom table to magento)
 
somesid
Sr. Member
 
Total Posts:  83
Joined:  2008-06-20
 

Hi,

Starting a new magento shop, we are coming along a problem that may become a big issue for us and may be relevant for other people.  We want to add to our shop several custom attributes “dropdown” BUT the values wouldn’t only be “simple text” but keys for database entries of a custom table.

We want the admin to be able to create an object in a custom module (let’s say a “Icon” module for example, with several fields, and one of this fields would be a key). No problem on this side, the module creator is really working great. Then we want to be able to select this key in a custom dropdown attribute (this way we can get values from the database in the front end and then get the full content of our custom table entry).

The idea is for the administrator to be able to manage complex entries and then, only select the reference in the product form.

We could imagine copy by hand the same key in the custom module and in the dropdown values of the attribute, but that will not satisfy our client, so the best way I could think of -not hacking too much magento- would be to add automatically those keys as custom dropdown attributes values when I’m adding/editing my custom entry (News).

To sum my problem:

I have a custom table, that I’m managing with a custom module :

CREATE TABLE `icons` (
  `
pictos_idint(11unsigned NOT NULL auto_increment,
  `
keyvarchar(50NOT NULL,
  `
titlevarchar(255NOT NULL,
  `
fichiervarchar(255NOT NULL,
  `
statussmallint(6NOT NULL default '0',
  `
created_timedatetime default NULL,
  `
update_timedatetime default NULL,
  
PRIMARY KEY  (`pictos_id`,`key`)
ENGINE=InnoDB DEFAULT CHARSET=utf8;

And I want to copy in my custom module, the keys as dropdown values (should be in: eav_attribute_option and eav_attribute_option_value).

So here are my two questions:
1. is it the best way to proceed ?
2. does anyone have a clue about the way of coding this ? the examples I find in the magento source code or in the forum doesn’t give me a clue of the way I should get the model, then the data, and then add new values in eav_attribute_option and eav_attribute_option_value.

Thx for any help smile
Will post if I find anything.

 
Magento Community Magento Community
Magento Community
Magento Community
 
somesid
Sr. Member
 
Total Posts:  83
Joined:  2008-06-20
 

Here is what I was able to come with, the code by itself loads the options of a dropdown of a custom attribute, then adds two values, then save them in the magento database.
I think it might be useful to understand the process of loading data then saving them in magento.

First lets suppose I created a custom module named Icons with the Module creator using the table from my previous post , and added a custom dropdown attribute named icon in magento the usual way.

I’m adding a new function in /app/code/local/Company/Icons/Block/Adminhtml/Icons/Edit/Tab/Form.php

public function addOptionValues() 
{
...
}

First lets get the model and the data:

$model_att Mage::getModel('eav/entity_attribute') ; // We get the model handling eav_attribute    
$code_att$model_att->getIdByCode('catalog_product','icon'); // We get the id of the attribute in eav_attribute
$att $model_att->load($code_att); // We load the infos of this attribute
        
$model_att_options Mage::getModel('eav/entity_attribute_source_table') ; // We get the model handling eav_attribute_option    
        
$attTable $model_att_options->setAttribute($att); // We set our attribute for this model 
                
$options $model_att_options->getAllOptions(false); //false -> we don't want to load the empty value

At this step here is what you have in $options:

array
  
=> 
    array
      
'value' => string '21' (length=2// id in eav_attribute_option 
      
'label' => string 'icon_1' (length=7// label on backend
  
=> 
    array
      
'value' => string '22' (length=2)
      
'label' => string 'icon_2' (length=7)

Now what we are missing are the label from the front end, so we go like that :

// code adapted from app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/Edit/Tab/Options.php
// Its getting all the values of the options on Frontend and Backend. 

$values = array();
 
//See linked file for getStores() code, it's coming from the same file I just told you about
$stores $this->getStores(); //We get Frontend and Backend.
          
      
foreach ($options as $option{
      
      
foreach ($this->getStores() as $store{
          $store_id 
$store->getData('store_id');
          
          
$storeValues $this->getStoreOptionValues($store_id);
          if (isset(
$storeValues[$option['value']])) {
              $value[$store_id] 
htmlspecialchars($storeValues[$option['value']]);
          
}
          
else {
              $value[$store_id] 
'';
          
}                
      }
      
    $values[] 
= new Varien_Object($value);
}

What I’ve got in $values ?

array
  
=> 
    
object(Varien_Object)[290]
      
protected '_data' => 
        array
          
=> string 'icon_1' (length=7)
          
=> string 'icon_front_1' (length=7)
      protected 
'_origData' => null
      
protected '_idFieldName' => null
      
protected '_isDeleted' => boolean false
  1 
=> 
    
object(Varien_Object)[293]
      
protected '_data' => 
        array
          
=> string 'icon_2' (length=7)
          
=> string 'icon_front_2' (length=7)
      protected 
'_origData' => null
      
protected '_idFieldName' => null
      
protected '_isDeleted' =>

And finally I’m adding new entries:

$value = array();
$order = array();
$delete = array();

// Adding two new options to my select

//If you execute code several time it will keep adding entries in eav_attribute_option 
//but will replace the values in eav_attribute_option_value
//If you want to edit you have to replace option_x by the right id from eav_attribute_option_value
$value['option_3'= array('0' => 'icon_3''1' => 'icon_front_3');
$order['option_3'=  '2';
$delete['option_3'=  '';

$value['option_4'= array('0' => 'icon_4''1' => 'icon_front_4');
$order['option_4'=  '3';
$delete['option_4'=  '';

// Building the final array of data
$results = array('value' => $value'order' => $order'delete' => $delete);

//Setting the option data, in the main data array
$att->setData('option',$results);

//Saving attribute
$att->save();

here is what we have in results :

array
  
'value' => 
    array
      
'option_3' => 
        array
          
=> string 'icon_3' (length=4)
          
=> string 'icon_front_3' (length=21)
      
'option_4' => 
        array
          
=> string 'icon_4' (length=4)
          
=> string 'icon_front_4' (length=23)
  
'order' => 
      
'option_3' => string '2' (length=1)
      
'option_4' => string '3' (length=1)
  
'delete' => 
    array
      
'option_3' => string '' (length=0)
      
'option_4' => string '' (length=0)

Instead of adding new values you may want to build an array with options values you already had in the eav_attribute_option_value table.
Add this after

$value = array();
$order = array();
$delete = array();

The following code

for($i=0$i count($values);$i++) {    
      $value[$options[$i][
'value']] $values[$i]->getData() ;
      
$order[$options[$i]['value']] ''.$i;
      
$delete[$options[$i]['value']] '';  
}

Now using that base, I’m able when I save an entry in my custom database to automatically add an option to my attribute, then select it the usual way in the product form. Finally in my template I can get the key value, and then load data from my custom table.

File Attachments
addAttributes.php  (File Size: 3KB - Downloads: 332)
 
Magento Community Magento Community
Magento Community
Magento Community
 
nekosan
Member
 
Avatar
Total Posts:  32
Joined:  2008-07-15
 

wow. this is great. I needed the same thing, with a custom dropdown, something that I can use to enable the customer to select a parent product for each product.
the thing is that I didn’t need where to start.

I’ll test your code and give you my impression about it

 
Magento Community Magento Community
Magento Community
Magento Community
 
nekosan
Member
 
Avatar
Total Posts:  32
Joined:  2008-07-15
 

as I see it, you add values from a custom module to your custom dropdown. In my case, I need to update the options table whenever the customer adds a new product. Cause any new product will be a possible parent product for the rest… hmm

 
Magento Community Magento Community
Magento Community
Magento Community
 
somesid
Sr. Member
 
Total Posts:  83
Joined:  2008-06-20
 

You would have to hack the core in order to do that. Probably somewhere in app\code\core\Mage\Adminhtml\controllers\Catalog\ProductController.php in editAction

A nthen add the SKU of the product you’re saving as a dropdown option. But it’s probably a tricky thing to do, ‘cause you will run really fast into some problems with editing and deleting products entries from you’re dropdown.

 
Magento Community Magento Community
Magento Community
Magento Community
 
nekosan
Member
 
Avatar
Total Posts:  32
Joined:  2008-07-15
 

I managed to find something in the sql table: eav_attribute
You see, just like you, I added a new attribute, dropdown. The attribute code is “parent”. Now when I look in that table, the source model for any dropdown is set for this source_model “eav/entity_attribute_source_table”. Now, the main method called in the admin part for a dropdown is from this class:
Mage_Eav_Model_Entity_Attribute_Source_Table as seen from the source_model field above.
The method is this one:

public function getAllOptions($withEmpty true)
    
{
        
if (is_null($this->_options)) {
            $this
->_options Mage::getResourceModel('eav/entity_attribute_option_collection')
                ->
setAttributeFilter($this->getAttribute()->getId())
                ->
setStoreFilter($this->getAttribute()->getStoreId())
                ->
setPositionOrder('asc')
                ->
load()
                ->
toOptionArray();
        
}
        $options 
$this->_options;
        if (
$withEmpty{
            array_unshift
($options, array('label'=>'''value'=>''));
        
}
        
//print_r($options);
        
return $options;
    
}
Now, what this method does, is get all records for this model “ eav/entity_attribute_option_collection”, for our attribute_id and store_id
then it populates an array with “label” and “value”.

All I did is change the source_model for my field in that table, i set it to “eav/entity_attribute_source_table2”. so I just copied the same class, gave it a new name, etc.
All I did then is change that method

public function getAllOptions($withEmpty true)
    
{     
        $options[] 
= array('label' => '''value'=>'');
        
$options[] = array('label' => 'Test1''value'=>'1');
        
$options[] = array('label' => 'Test2''value'=>'2');
        
$options[] = array('label' => 'Test3''value'=>'3');
        
$options[] = array('label' => 'Test4''value'=>'4');
        
$this->_options $options;
        
print_r($options);
        return 
$options;
    
}

For now I just prepopulate the list. If I edit a product, I can see the field, I see the list values, and they are all saved in the proper table. I can edit them, etc.
All I have to do now is get the products collection and make an array out of that, with value being the “product_id”.
I don’t know if it’s the best solution but it works. And it should work with any other table. Anyway, if I get it to work as I want I will post the entire solution and the code for it
Thanks for the info so far somesid

oh, btw. Values chosen for a product (for the dropdown type anyway) are stored in this table: catalog_product_entity_int

 
Magento Community Magento Community
Magento Community
Magento Community
 
Rinku
Member
 
Total Posts:  41
Joined:  2008-09-17
New Delhi
 

Hello,

I added a new attribute with multiple option. The module name is “Language” and the options are “English, Hindi”. When I save the product it stores the IDs of the language options with ‘,’ seperated. Now I want to show these languages on front. Now please let me know how can I get my value from its id. Actually I want to show “English” in place of “3”. Please help me.

Thanks
Sandeep

 
Magento Community Magento Community
Magento Community
Magento Community
 
carcomp
Jr. Member
 
Total Posts:  21
Joined:  2011-06-15
 

And here it is, so you can do it anywhere!  I’ve added this to a soap call.  And yes, I know its a mess but it works and thats enough for me.

require_once 'app/Mage.php';
    
Mage::app(); 
    
    
    
//echo "<PRE>";
    
    
$attribute_model        Mage::getModel('eav/entity_attribute');
    
$attribute_options_modelMage::getModel('eav/entity_attribute_source_table') ;
    
$attribute_code         $attribute_model->getIdByCode('catalog_product''product_type'); // <-- change to your attribute code
    
$attribute              $attribute_model->load($attribute_code);
    
$attribute_table        $attribute_options_model->setAttribute($attribute);
    
$options                $attribute_options_model->getAllOptions(false);
    
//var_dump($options);
    
    // code adapted from app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/Edit/Tab/Options.php
    // Its getting all the values of the options on Frontend and Backend. 

    
$values = array();
     
//See linked file for getStores() code, it's coming from the same file I just told you about
    
    
    
$stores Mage::getModel('core/store')
        ->
getResourceCollection()
        ->
setLoadDefault(true)
        ->
load();
         
         
         echo 
"<pre>";
    
         
         
    foreach (
$options as $option{
          
        
foreach ($stores as $store{
            $store_id 
$store->getData('store_id');
              
            
$valuesCollection Mage::getResourceModel('eav/entity_attribute_option_collection')
                ->
setStoreFilter($store_idfalse)
                ->
load();
            
            
$justValues $valuesCollection->getData();
            
            foreach (
$justValues as $thevalue{
                
if ($option['value'== $thevalue['option_id']{
                  $values[] 
= new Varien_Object($thevalue);
                
}
            }
          }
          
    }
    
    
    $value 
= array();
    
$order = array();
    
$delete = array();
    
$count 0;
    
    for(
$i=0$i count($values);$i++) {  
        $tmp 
$values[$i]->getData();
        
        
$value['option_' $i][] $tmp['value'];
        
$value['option_' $i][] $tmp['value'];
        
        
$order['option_' $i][] ''.$i;
        
$delete['option_' $i][] '';  
        
$count++;
    


    
    
// Adding two new options to my select
    
$value[] = array('0' => 'TESTING''1' => 'TESTING_FRONT'); // <-- change these to your values you want to add
    
$order[] =  $count 1;
    
$delete[] =  '';
    
    
// Building the final array of data
    
$results = array('value' => $value'order' => $order'delete' => $delete);
    
    
    
//Setting the option data, in the main data array
    
$attribute->setData('option',$results);
    
    
//Saving attribute
    
$attribute->save();
 
Magento Community Magento Community
Magento Community
Magento Community
Magento Community
Magento Community
Back to top