【问题标题】:Retrieving POST from $form object with doctrine and symfony使用学说和 symfony 从 $form 对象中检索 POST
【发布时间】:2015-06-16 17:08:29
【问题描述】:

我的问题
表单请求/POST 中的这两行有什么区别?

  • $article->getComments() as $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 是一个带有一些 cmets 的对象。

$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
       }
    }
}

文章类型 添加文章内容并添加cmets集合

【问题讨论】:

    标签: php forms symfony post doctrine


    【解决方案1】:

    $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();
    

    这有帮助吗?

    【讨论】:

    • 好的,所以 $article 即使在 $form->bind($request) 之后也保持不变。我以为$form->bind($request)会根据表单提交的数据更新$article。
    • 没错 - 您传递给createForm() 的对象没有Form::bind()期间更新为新值
    猜你喜欢
    • 1970-01-01
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-11
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    相关资源
    最近更新 更多