【问题标题】:Symfony2: Persisting user entry to the databaseSymfony2:持久化用户进入数据库
【发布时间】:2015-08-08 11:09:00
【问题描述】:

我在 Symfony2 中有一个显示在 Twig 模板上的表单。我想知道将用户条目保存到数据库中的控制器的业务逻辑是什么?我尝试了下面的代码,但它没有插入到数据库中。非常感谢:)

 /**
     * @Route("/lot", name="sort")
     * @Template()
     */
    public function bestAction(Request $request)
    {
            $quest = new quest();
            $form = $this->createForm(new QuestType(), $quest, array(
//                'action' => $this->generateUrl('best'),
                'method' => 'POST',
            ));

        $form->handleRequest($request);

        if($entity->isValid()){

            $em = $this->getDoctrine()->getEntityManager();
            $entity = $em->getRepository('IWABundle:quest');

            $em->persist($entity);
            $em->flush();

        }

        return $this->render('IWABundle:Default:index.html.twig', array(
            'form' => $form->createView()
        ));
    }

{% block form %}
                  {{ form_start(form, {'action': path('sort'), 'method':'POST'}) }}
                  {{ form_start(form.email) }}
                  {{ form_start(form.firstname) }}
                  {{ form_start(form.enqiry) }}
                  {{ form_end(form) }}
          {% endblock %}

【问题讨论】:

  • 您在使用表单时正在填写$quest 对象的详细信息,但之后您将获得一个存储库,然后尝试将其持久化到数据库中。如果您删除 $entity = $em->getRepository('IWABundle:quest'); 并将 $quest 对象持久化到数据库中。

标签: database forms symfony submit


【解决方案1】:

您将实体 ($quest) 与实体管理器混为一谈:

/**
 * @Route("/lot", name="sort")
 * @Template()
 */
public function bestAction(Request $request)
{
    // 1) Create your empty entity
    $quest = new Quest();

    // 2) Create your form from its type and empty entity
    $form = $this->createForm(new QuestType(), $quest, array(
        'method' => 'POST',
    ));

    // 3) Handle the request
    $form->handleRequest($request);

    // 4) Check if the form is valid
    if ($form->isValid()) {
        // 5) Get the entity manager
        $em = $this->getDoctrine()->getEntityManager();

        // 6) Persist the new entity and flush the changes to the database
        $em->persist($quest);
        $em->flush();
    }

    return $this->render('IWABundle:Default:index.html.twig', array(
        'form' => $form->createView()
    ));
}

查看how to persist objects to the databasehow to manage form submission 的官方文档。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    • 2022-08-13
    • 1970-01-01
    相关资源
    最近更新 更多