A typical Developer Blog
by Gordon Franke
Icon

Wie kann ich Werte nach dem Abschicken eines Formulars hinzufügen?

Ich möchte die user id des aktuell eingelogten zum formular hinzufügen. Ich könnte ein hidden feld benutzen, aber das ist nicht sicher. Also rufe ich die updateObject($values) methode zwischen isValid() und save() auf.

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.

Ähnliche Artikel bereitgestellt von Yet Another Related Posts Plugin.

Author:

Category: symfony, Uncategorized

Tagged: , , ,

5 Responses

  1. Hugo sagt:

    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é sagt:

    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 sagt:

    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 sagt:

    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 sagt:

    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