Spongeboy
Spongeboy

Reputation: 2232

Magento and unsetting a custom boolean attribute

I've added an attribute to a customer address entity. Attribute setup code is as follows-

'entity_type_id'=>$customer_address_type_id,
'attribute_code'=>'signature_required',
'backend_type'=>'int',
'frontend_input'=>'boolean',
'frontend_label' => 'Signature required',
'is_global' => '1',
'is_visible' => '1',
'is_required' => '0',
'is_user_defined' => '0',

I have then -

I am now getting the attribute saved to the database when the checkbox is checked. However, it is not being unset when checkbox is unchecked (I'm guessing due to checkbox input not being 'post'-ed if unchecked.

What is the best way to uncheck this? Should I add a default value of 0? Or unset/delete the attribute before save in the controller? Should I add get/set methods to the model?

Upvotes: 1

Views: 5070

Answers (3)

Jimmy Pelton
Jimmy Pelton

Reputation: 11

You are right, the problem is that unchecked checkboxes aren't sent through on the POST request.

You can fix this by putting a hidden form input with a value of '0' before your checkbox like this:

<input type='hidden' name='my_checkbox' value='0'>
<input type='checkbox' name='my_checkbox' value='1'>

Now if the checkbox is checked it will send through a value of '1', if it is unchecked it will send a value of '0'.

I should note that this is only true in PHP because when two identical POST values are sent in, it takes the last one. Different server side languages may handle this differently

Upvotes: 0

clockworkgeek
clockworkgeek

Reputation: 37700

I had a similar problem today, found the various guides to be tedious and worked around it by changing using a "select" instead of a "checkbox" and setting the "source" to eav/entity_attribute_source_boolean which gives a simple "Yes"/"No" drop-down and saves correctly without modification.

Upvotes: 4

Spongeboy
Spongeboy

Reputation: 2232

In the end, I overrode the setData method in my custom model.

I did find some good resources on trying to override/overload (both terms are common) controllers/routers.

Also of note -

'frontend_input'=>'boolean',

should be

'frontend_input'=>'checkbox',

Upvotes: 3

Related Questions