A typical Developer Blog
by Gordon Franke
Icon

How can i add some values after form submit?

i won’t to add the user id from the current logged in user to the form. I can add a hidden field, but this is not really secure. I simple call the updateObject($values) methode between isValid() and save().

1
2
3
4
5
6
7
8
9
10
11
protected function processForm(sfWebRequest $request, sfForm $form)
{
  $form->bind($request->getParameter($form->getName()));
  if ($form->isValid())
  {
    $form->updateObject(array('user_id' => $this->getUser()->getAttribute('user_id', null, 'sfGuardSecurityUser')));
    $article = $form->save();
 
    $this->redirect($this->generateUrl('article_detail', $article));
  }
}

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Author:

Category: symfony, Uncategorized

Tagged: , , ,

5 Responses

  1. Hugo says:

    Hello,

    There is a better way to set the default value of a Propel / Doctrine object from within its associated form object. You simply have to set the related object field like below :

    // First way
    $object = new myModelObject();
    $object->setUserId($this->getUser()->getId()); // getId() wraps the sfGuardUser id
    $form = new myModelForm($object);

    // Second way
    $form = new MyModelForm();
    $form->getObject()->setUserId($this->getUser()->getId());

    That’s all ;)

    Hugo.

    Hugo’s last blog post..Sensio Labs recrute un développeur PHP 5 / MySQL Junior

  2. Éric Rogé says:

    I agree.

    If I were you, to keep a smaller controler and a more reusable form, I would pass the user as an option of the form.

    $this->form = new MyForm($myObject, array(‘user’ => $this->getUser());

    Then, inside the form, you can get back the user :

    $user = $this->getOption(‘user’);

    The less you do in controlers, the more flexible is your application !

  3. Hugo says:

    Passing the user object as an option is also a good way. These two ways offers the availability to unit test the model.

    Hugo’s last blog post..Sensio Labs recrute un développeur PHP 5 / MySQL Junior

  4. Daniel says:

    Or you can just override the doSave method in your model which is, to my mind, the cleanest way. The user id doesn’t depend on the form (or the other way around). The model is responsible for checking security constraints and the like (which the association of a database record with a user often is).

    Cheers, Daniel

  5. LBO says:

    I can’t agree that passing user_id as hidden fields is insecure – just use validator that will compare user_id field with session user id.

    Cheers, Alan

Leave a Reply

CommentLuv badge