CakePHP Validation Nightmare

So I had this form with radio buttons and some database fields that do not allow NULLS which was working before I started tinkering with some fancy features.

After a few minutes of modifying the code to use a JQuery star rating plugin for the radio buttons, I was stuck with a form that wouldn’t save even though the validates $this->ModelName->validates(array('fieldList'=>array())) method returned true.

Printing out the posted data in $this->data showed me that my radio buttons which were created individually were sending empty strings with no data.

I was almost knocking my head against the wall and pulling out my hair when I decided to turn off the validation for the radio button fields just to see if that would make the form save. But no joy!

Eventually, by using Firefox‘s webdeveloper plugin I examined the form and noticed there was one hidden input with the name of the radio button field for each of the radio buttons.

How do I remove these hidden input fields? According to the CakePHP manual, a hidden field is usually attached to form elements such as radio buttons, and check boxes, so that even when none of the options get selected, there will be an entry for that field in the return $this->data array.

Then I found out from the manual that you can remove the hidden fields by specifying an option for ‘hiddenField’=>false as part of added parameters for the form input method.

I removed all the hidden fields from all but the very first radio button just to keep things normal. That means I specified ‘hiddenField’=>false for each radio button excluding the first one in the group.

This meant that my form now submitted data normally in each of the radio button groups.

But despite fixing this there was still a problem as my database only saved some fields and ignored the other form fields. I quickly realised that I had whitelisted several fields and forgot to add the news fields I had added when I modified the database structure.

That solved the problem of the partial saving altogether.

Finally, I decided to allow NULLS for the fields that were allowed to be empty in order to ensure that it saves even when none of the radio button options are selected which was what I needed.

Goodness gracious!

Advertisements