How to save checkbox values in database in magento ?
My code is:

$fieldset->addField('expertise', 'checkboxes', array(
    'name'      => 'expertise',
    'label'     => Mage::helper('checkout')->__('Expertise Area'),
    'required'  => true,
    'values'   =>array('Php','.Net')

To make it working well you need to:

1) In your Form class, before $form->setValues($data); add the following:

if (!is_array($data['expertise'])) {
    $data['expertise'] = explode(',', $data['expertise']);

2) In your Controller class, before $model->setData($data); add the following:

if (is_array($data['expertise'])) {
    $data['expertise'] = implode(',', $data['expertise']);

Moreover, input component of "checkbox" type is not standard in Magento and it works incorrectly in some cases. The best solution here is to use "multiselect" component:

    'expertise', 'multiselect', array(
    'name'     => 'expertise',
    'label'    => Mage::helper('checkout')->__('Expertise Area'),
    'required' => true,
    'values'   => array(
            'label' => 'Php',
            'value' => 'php'
            'label' => '.Net',
            'value' => 'dotnet'

Please consider the following things.

For example:

if your attribute is expertise Then in your controller saveAction() when saving the checkbox data do

$expertise = isset($your_form_Data['expertise']) ? 1 : 0;

For Grid and Form Page

In your controller you should have Mage::register(...)->getData() or Mage::register(...)

public function editAction()
     Mage::register('example_data', $model);

On your form _prepareForm()

$model = Mage::registry('example_data'); // NOTE registry('example_data'); NOT registry('example_data')->getData();

$fieldset->addField('entire_range', 'checkbox', array(
      'checked'    => $model->getExpertise()==1 ? 'true' : 'false',

On your grid _prepareColumns()

$this->addColumn('expertise', array(
    'type'     => 'checkbox',
    'index'    => 'expertise',
    'values'   => array(1,2),
    'field_name' => 'checkbox_name',

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.