La huitième partie de ce tutoriel abordera la mise en place de formulaires, à travers l’envoi de commentaires sur notre blog :
- mise en place de notre formulaire à l’aide du composant sfForm
- mise en place des validateurs du formulaire
- validation du formulaire depuis l’action du module posts
- découverte des notifications Symfony via setFlash et getFlash
Des questions, remarques ou suggestions ? N’hésitez pas à me suivre sur Twitter, rejoindre la page Facebook ou suivre le flux RSS du blog.
Sources
Formulaire CommentForm.class.php :
useFields(array(
'author', 'comment'
));
$this->widgetSchema['comment'] = new sfWidgetFormTextarea();
$this->widgetSchema->setLabels(array(
'author' => 'Votre pseudonyme :',
'comment' => 'Votre commentaire :',
));
$this->widgetSchema->setFormFormatterName('list');
$this->widgetSchema->setNameFormat('comment[%s]');
$this->validatorSchema['author'] = new sfValidatorString(array('required' => true), array('required' => 'Champs obligatoire !'));
$this->validatorSchema['comment'] = new sfValidatorString(array('required' => true, 'min_length' => 10), array('required' => 'Champs obligatoire !', 'min_length' => '%min_length% caractères minimum !'));
}
}L’action executeShow du module posts :
public function executeShow(sfWebRequest $request)
{
$this->post = $this->getRoute()->getObject();
$postComment = new Comment();
$postComment->setPost($this->post);
$this->commentForm = new CommentForm($postComment);
if ($request->isMethod('post'))
{
$this->commentForm->bind(
$request->getParameter($this->commentForm->getName())
);
if ($this->commentForm->isValid())
{
$this->commentForm->save();
$this->getUser()->setFlash('success', 'Commentaire posté !');
$this->redirect('posts_show', $this->post);
}
else
{
$this->getUser()->setFlash('error', 'Des champs sont incomplets ou invalides.');
}
}
}
