Thursday, March 22, 2012

setValue() For Form Fields in Symfony

If you want to overwrite the value of a field in an action, you have to a create a new method for the form. Usually  people think that setDefault method is good for that. No. setDefault set a default value to a field. However if the field contains a value, setDefault won't overwrite it. Let's see an example: You put a word to the "location" field then you save the form to the database. after that, you want to see another value in the "location" field:
// add this method to the form class
public function setValue($field, $value) {
  // set the value for this request
  $this->values[$field] = $value; 
  // override the value entered by the user
  $this->taintedValues[$field] = $value;
  // force a refresh on the field schema
  $this->resetFormFields();
}


// actions.class.php ... save method ...
if ($this->form->isValid())
{
  $this->form->save();

  // the magic
  $this->form->setValue('location', 'a new value');

  // you can set an empty value also
  $this->form->setValue('location', '');

  // if location is a checkbox, you have to set null to uncheck it
  $this->form->setValue('location', null);

...

No comments:

Post a Comment