【问题标题】:Symfony 4, when I try to submit a form it does not workSymfony 4,当我尝试提交表单时它不起作用
【发布时间】:2017-12-10 17:26:32
【问题描述】:

提前感谢那些想帮助我的人。我正在学习 symfony 4,并且正在测试如何通过从表单中获取数据来更新数据库。所以我确保它在 id 的基础上寻找一个表格,并用表格的正确值填充表格。但是当我提交时,表单-> isSubmitted 条件永远不会被验证。你有什么建议吗?

    public function updateArticle(Request $request, $id)
  {
    $em = $this->getDoctrine()->getManager();
    $article = $em->getRepository(Article::class)->find($id);
    if (!$article) {
        throw $this->createNotFoundException(
            'No article found for id '.$id
        );
    }
    $articletext = $article->getArticle();
    $title = $article->getTitle();
    $image = $article->getFeatureimage();
    $category = $article->getCategory();
    $author = $article->getAuthor();
    $article->setArticle($articletext);
    $article->setTitle($title);
    $article->setFeatureimage($image);
    $article->setCategory($category);
    $article->setAuthor($author);
    $form = $this->createFormBuilder($article)
        ->add('article', TextareaType::class)
        ->add('title', TextType::class)
        ->add('featureimage', FileType::class, array('data_class' => null,'required' => true))
        ->add('category', TextType::class)
        ->add('author', TextType::class)
        ->add('save', SubmitType::class, array('label' => 'Inserisci articolo'))
        ->getForm();
    if ($form->isSubmitted()) {
        $article = $form->getData();
        print_r($article);
        return $this->redirectToRoute('blog');
      }
      else
        return $this->render('insert.html.twig', array(
          'form' => $form->createView(),
        ));
  }

【问题讨论】:

    标签: php symfony symfony4


    【解决方案1】:

    您忘记了处理数据的行。 Look at the doc 在 if 条件之前添加这一行:

    //form creation as you did but it's better to construct the form via the FormType
    
    $form->handleRequest($request);
    if ($form->isSubmitted()){
    //Do some stuff
    

    【讨论】:

    • 您还应该测试表单是否有效。 if ($form->isSubmitted() && $form->isValid()) {}
    • 太棒了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    相关资源
    最近更新 更多