0

I am currently looking to build a banner module that will allow a Magento admin user to upload banners to appear on their home page and then select what store views they want these to appear on as well as setting what customer groups they want the banner to appear for.

I have created a single table model that is managed through the admin area and have the store view selector working correctly but cant work out how I can obtain a list of the websites available customer groups and display them in a multiselect form element to enable the admin to choose which customer group the banner is for when creating or editing a banner item.

Can somebody advise the best way to obtain a list of available customer groups and display these in a multiselect form element?

1

You can get a list of the customer groups via:

Mage::getModel('customer/group')->getCollection();

From here, you can run a function that generates a simple key->value style array.

'0'=>'Retailer',
'1'=>'Wholesale'
...

You can use code similar to this: (not tested)

function getAllCustomerGroupOptions(){
    $all = Mage::getModel('customer/group')->getCollection();
    $options = array();
    foreach($all as $group){
        $options[$group->getId()] = $group->getData('customer_group_code');
    }
    return $options;
}

Once you've returned this as a key/value array, you can call the function within your form field:

$fieldset->addField('groups', 'multiselect', array(
  'label'     => $this->__('Select a Group'),
  'name'      => 'groups',
  'values'    => $this->getAllCustomerGroupOptions();
));

That should do it.
I've not tested the code, but if it doesn't work, this should give you a starting point.

| improve this answer | |
  • 1
    Works perfectly! Thanks for your help! :-) – Ryan Sep 1 '14 at 13:37
  • Just one corrections: It should be $options[] = array('value'=>$group->getId(),'label'=>$group->getData('customer_group_code')); inside foreach. – JohnyFree Feb 8 '15 at 10:05
  • @JohnyFree when used within the 'values' key of the addField function, then using 'value' and 'label' parings isn't the best course of action. If this were a source model for a system.xml field, then you would be correct. – Dan Hanly Feb 8 '15 at 23:14
0

Better solution (tested on magento 1.9):

    $fieldset->addField('customer_group_id', 'select', array(
        'name'      => 'customer_group_id',
        'label'     => $this->_getHelper()->__('Customer Group'),
        'title'     => $this->_getHelper()->__('Customer Group'),
        'required'  => true,
        'values' => Mage::getSingleton('customer/customer_attribute_source_group')->getAllOptions()
    ));
| improve this answer | |

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.