我的问题
表单请求/POST 中的这两行之间有什么区别?
- $article->getComments() 作为$comment
- $form->get('Comments')->getData() as $comment
上下文
实体文章
class Article
{
private Comments
public function __construct() {
$this->Comments = new'Doctrine'Common'Collections'ArrayCollection()
}
public function getComments()
{
return $this->comments
}
表格请求
$article是一个带有一些注释的对象。
$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
}
}
}
文章类型添加文章内容并添加评论集合
在$form->bind($request)
所做的所有工作深处,Symfony的表单系统从HTTP请求中读取所有数据,并将其分配给表单的底层数据对象。因此,当您运行$form->getData()
时,它会返回与请求中找到的值合并的表单默认值。
让我们走一遍
// 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();
这有帮助吗?