Retrieving POST from $form object with doctrine and symfony

665 Views Asked by At

MY QUESTION
What the difference between those two lines in a form request/POST?

  • $article->getComments() as $comment
  • $form->get('Comments')->getData() as $comment

CONTEXT

ENTITY ARTICLE

 class Article
 {
     private Comments
     public function __construct() {
       $this->Comments = new\Doctrine\Common\Collections\ArrayCollection()
     }
     public function getComments() 
     {
           return $this->comments
     }

FORM REQUEST

$article is an object with some comments.

$form = $this->createForm(new ArticleType(), $article);
$request = $this->getRequest();
if($request->getMethode() == 'POST'){
    $form->bind($request);
    if($form->isValid()) {
       $liste_comments = array();
       $liste_comments_bis = array();
       foreach($article->getComments() as $comment){
           $liste_comments[] = $comment
       }
       foreach($form->get('comments')->getData() as $comment_bis){
           $liste_comments_bis[] = $comment_bis
       }
    }
}

ARTICLETYPE add article contenu and add a collection of comments

1

There are 1 best solutions below

2
On

Deep inside all the work done by $form->bind($request), Symfony's form system reads all of the data from the HTTP requests and assigns it to the form's underlying data object. So, when you run $form->getData() it's returning the form's default values merged with values found in the request.

Let's walk through it

// Create a form object based on the ArticleType with default data of $article
$form = $this->createForm(new ArticleType(), $article);

// Walk over data in the requests and bind values to properties of the
// underlying data. Note: they are NOT bound to $article - $article just
// provides the defaults/initial state
$form->bind($request);

// Get the Article entity with bound form data
$updatedArticle = $form->getData();

// This loops over the default comments
foreach ($article->getComments() as $comment) {}

// This loops over the submitted comments
foreach ($updatedArticle ->getComments() as $comment) {}

// For the purpose of my example, these two lines return the same thing
$form->get('comments')->getData();
$form->getData()->getComments();

Does that help?