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?

2 Answers 2

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.

3
  • 1
    Works perfectly! Thanks for your help! :-)
    – Ryan
    Commented Sep 1, 2014 at 13:37
  • Just one corrections: It should be $options[] = array('value'=>$group->getId(),'label'=>$group->getData('customer_group_code')); inside foreach.
    – JohnyFree
    Commented Feb 8, 2015 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
    Commented Feb 8, 2015 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()
    ));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.