[Symfony] Overwrite a value in a form

It happen sometimes that you have to set/override a value within a form but without using a hidden field (that can be overridden)

Here is a short solution to set the user id in the object we are going to save.

Let's say that we have an object PersonnalData linked to the sfGuardUserProfile

In your PersonnalDataForm.class.php :

class PersonnalDataForm extends BasePersonnalDataForm {
 
    public function configure() {
    }
 
    //public function processValues($values = null) {  // only in 1.2
    public function processValues($values) { // 1.3 - 1.4
        $values['user_id'] = $this->getOption('user_id');
        return parent::processValues($values);
    }
 
 
}

$this->getOption('user_id') is a mechanism to pass variables from outside the form to it. To set it, you must use the second argument of the form's constructor.

In your action :

public function executeMyaction(sfWebRequest $request) {
        //                                             setting an array containg the variable we want to use in our form
        $this->form = new PersonnalDataForm(null, array('user_id' => $this->getUser()->getProfile()->getId() ));
 
        if($request->isMethod('post')) {
            $this->form->bind($request->getParameter($this->form->getName()));
            if($this->form->isValid()) {
                $this->form->save();
            } else {
                //echo 'not valid';
            }
        }
    }

Haut de page