Customising Symfony forms – be careful with base class inheritence

Background

Recently I was working on a form for updating a couple of very simple values for a single table. When creating such forms, where we only need a subset of the available columns to be editable, we always have the option of either unsetting the fields we don’t need, or overriding the widgetSchema. In this case, I opted for the latter, since I only needed to edit 2 columns out of a possible 10, I didn’t think adding 8 fields to the unset() function was the cleanest way. The following examples contain obfuscated data.

Overriding the widget schema

public function configure()
{
  $this->setWidgets(array(
    'amount'               => new sfWidgetFormInput(),
    'reduced_amount' => new sfWidgetFormInput(),
    ));
 
   //Labels and decorator stuff here
}

My plan was to inherit the validators that already exist in the base class, since they do the job for what I need.

The error

The form worked fine for an insert, but when I came to update an existing record, the error was quite strange:

SQLSTATE[23505]: Unique violation: 7 ERROR: 
  duplicate key value violates unique constraint 
  "body_fee_version_pkey"

The problem it seemed was that my versionable behaviour was not incrementing the version value before attempting to insert a new version record. After a long period of debugging the versionable behaviour, along with some of my other custom behaviours, I was no closer to a solution.

I started to dig into the form classes, working backwords through all the object update methods, save, dosave, etc. Until I finally stumbled across this line:

$this->values = $this->validatorSchema->clean(
   self::deepArrayUnion($this->taintedValues, 
   self::convertFileInformation($this->taintedFiles))
 );

Before this call, everything seemed ok, but after this call, my values array, which at this stage only contained the two fields that had been posted, now suddenly included a value for all the fields in the table. Why? It then occurred to me that the entire validator schema was being processed, not just the fields that are actually posted! This means that all the validators that are required=false will silently return a “clean” value, which is most likely the database default.

So what did this mean? Well, it meant that the validator was “cleaning” all the columns that had not been submitted with the form, including the version column, which was being set to null. When the versionable behaviour kicked in, it read this null value and incremented by 1 for the next version, which then became 1 – a version which of course already existed, causing the error.

The solution

The solution is blindingly simple, we don’t just declare the widget schema, we must also declare the validator schema. Whilst this seems like it makes sense, I feel that it is a shame that I have to essentially copy and paste the necessary validators from the base class. The alternative of course would have been to unset the offending fields, but then we are back to option 1 above, unsetting 8 of 10 fields when it seems cleaner just to declare the 2 fields I actially need.

  $this->setWidgets(array(
    'amount'               => new sfWidgetFormInput(),
    'reduced_amount' => new sfWidgetFormInput(),
    ));
 
// Messages declared here as array since they are the same
 
$this->setValidators(array(
  "amount"  => new sfNumberValidator(
                       array('required' => true), $messages),
  "reduced_amount" => new sfNumberValidator(
                       array(), $messages),
 ));
 
   //Labels and decorator stuff here

Conclusion

I have been working with Symfony for over a year and a half, and with Symfony forms since they were born – and yet I was still caught out by something that seems quite simple, because I assumed it would be ok. There are so many things that could have alerted me to this problem and saved me a lot of time, for example if any of the extra fields had been required=true then at least I would have had some form errors to give me a clue!

I may suggest that the default behaviour should be to only process the validators that match the widgets, or maybe at least for the form to err if extra validators are found that are not used, as I feel that this is a mistake that others could make, and as I mentioned above, it’s a shame that we have to re-declare validators that are already present in the base class.

5 Comments so far

  1. joes on March 23rd, 2009

    I’ve had the same issue as you (wanting to keep only a few fields but not wanting to have many ugly unset:s in the code) so I stuck this method into BaseFormDoctrine:

    /**
    * unsetAllFieldsExcept
    *
    * Unsets all fields except for the ones defined in func_get_args
    *
    * @return void
    **/
    public function unsetAllFieldsExcept()
    {
    $keepFields = func_get_args();
    foreach($this as $key => $value) $baseFields[] = $key;
    $temp = array_diff($baseFields, $keepFields);
    foreach ($temp as $unsetField) unset($this[$unsetField]);
    }

    Using the above method in this case would allow one to use only the ‘amount’ and ‘reduced_amount’ of the form by doing:

    public function configure()
    {
    $this->unsetAllFieldsExcept(‘amount’, ‘reduced_amount’);
    }

  2. Russ on March 23rd, 2009

    Nice idea, maybe it’s something that can be added to the core?

    It would be better off in sfForm I guess… Have you submitted a patch?

  3. joes on March 24th, 2009

    This kind of method has already been proposed to symfony in http://trac.symfony-project.org/ticket/5525. Slightly different implementation, but very much the same thing…

  4. […] ran into this same problem, for which Symfony fails to offer a sensible error message: It then occurred to me that the entire […]

  5. Marcelo on November 30th, 2010

    Hi Russ, I have a problem here not like you but has to do with forms and unset.

    Situation: I have 3 embed forms, I’m going to use just one, the other two will be unset through a select option. But if this form has required fields no filled in the validation page I will lose the unset embed forms but I still have my select options which won’t work properly because the unset embed forms.

    Do you have some idea ?

Leave a reply