php - 填充多个表单 Symfony2

标签 php forms symfony formbuilder

我有一个 Controller ,我正在其中创建一个开放作业列表并通过 Twig 将它们填充到表中。 我现在想要的是每行的最后一个字段是一个上传表单,以便您可以将文件添加到一个特定的作业。不幸的是,我不知道如何在一个 Controller 中处理多个表单的表单请求。

这是我现在拥有的 Controller :

/**
 * @Route("/job/pending", name="pendingJobs")
 */
public function jobAction(Request $request)
{
    $this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to access this page!');

    $em = $this->getDoctrine()->getManager();
    $file = new File();
    $form = $this->createFormBuilder($file)
        ->add('file')
        ->add('job','entity',array(
            'class' => 'AppBundle:Job',
            'choice_label' => 'insuranceDamageNo',
        ))
        ->add('save', 'submit', array('label' => 'Create Task'))
        ->getForm();

    $form->handleRequest($request);

    if ($form->isValid()) {

        $job = $em->getRepository("AppBundle:Job")->find($form->getData()->getJob());

        $file->setFile($form->getData()->getFile());
        $file->setPath($form->getData()->getPath());
        $file->setJob($job);

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

        return $this->redirectToRoute("pendingJobs");
    }



    $jobs = $em->getRepository("AppBundle:Job")->findBy(array(
        'receipt' => true,
        'receiptStatus' => true,
    ));

    return $this->render(
        'default/pending.html.twig',
        array(
            'jobs' => $jobs,
            'form' => $form->createView(),
        )
    );


}

该表单工作完美,除了它只是一种表单并且“作业”实体是一个下拉列表之外。如果可能的话,我希望为每个作业“预先选择”它以获得正确的 ID。

我发现了一些关于“createNamedBuilder”的信息HERE (最后一篇文章)但它是法语的,我既不懂法语,也不懂 API完全有帮助。

我考虑了 $jobs 的 foreach,但是如何分离表单句柄?

任何提示表示赞赏!

最佳答案

在 Controller 中创建三个操作。一个用于主页,一个用于每个上传表单,一个用于处理表单:

/**
 * @Route("/job", name="pendingJobs")
 */
public function jobAction(Request $request) {
    $em = $this->getDoctrine()->getManager();

    $jobs = $em->getRepository("AppBundle:Job")->findAll();

    return $this->render(
                'default/pending.html.twig', array(
                'jobs' => $jobs,
            )
    );
}

/*
 * renders an uploadform as a partial from jobAction
 */
public function jobrowAction(Request $request, Job $job) {
    //$this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to access this page!');

    $em = $this->getDoctrine()->getManager();

    $file = new File();
    $file->setJob($job); // so that we know to what job this upload belongs!

    $form = $this->createUploadForm($file, $job->getId());

    return $this->render(
                'default/pending_job_row.html.twig', array(
                'job' => $job,
                'form' => $form->createView(),
            )
    );
}

/*
 * renders and processes an uploadform
 * 
 * @Route("/job/{id}/update", name="job_upload")
 * @Method("POST")
 */
public function uploadAction(Request $request, $id) {
    $em = $this->getDoctrine()->getManager();

    $file = new File();

    // this time we set the job property again cause we only receiced the jobId from the route
    $job = $em->getRepository("AppBundle:Job")->findOneBy(array('id' => $id));
    if (!$job) {
        throw $this->createNotFoundException('Unable to find Job entity.');
    }
    $file->setJob($job);

    $form = $this->createUploadForm($file, $id);
    $form->handleRequest($request);

    if ($form->isValid()) {

        $job = $em->getRepository("AppBundle:Job")->find($form->getData()->getJob());

        $file->setFile($form->getData()->getFile());
        $file->setPath($form->getData()->getPath());
        $file->setJob($job);

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

        return $this->redirectToRoute("pendingJobs");
    }

    // if the form is not valid show the form again with errors
    return $this->render(
                'default/error.html.twig', array(
                'form' => $form->createView(),
            )
    );
}

private function createUploadForm(File $file, $jobId)
{
    $form = $this->createFormBuilder($file, array(
                'action' => $this->generateUrl('job_upload', array('id' => $jobId)),
                'method' => 'POST',
            ))
            ->add('file')
            ->add('save', 'submit', array('label' => 'Create Task'))
            ->getForm();

    return $form;
}

然后制作两个 Twig 文件:

{# default/pending.html.twig #}

{% extends 'base.html.twig' %}

{% block body %}
    <table>
        {% for job in jobs %}
            <tr>
                <td>{{ job.title }}</td>
                <td>{{ render(controller('AppBundle:Default:jobrow', { 'job': job })) }}</td>
            </tr>
        {% endfor %}
    </table>
{% endblock %}

和:

{# default/pending_job_row.html.twig #}

{{ form(form) }}

在您的文件实体中缺少两种方法:

/**
 * Set job
 *
 * @param \AppBundle\Entity\Job $job
 *
 * @return File
 */
public function setJob(\AppBundle\Entity\Job $job = null)
{
    $this->job = $job;

    return $this;
}

/**
 * Get job
 *
 * @return \AppBundle\Entity\Job
 */
public function getJob()
{
    return $this->job;
}

关于php - 填充多个表单 Symfony2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33752126/

相关文章:

javascript - 在 Parse.com 上注册 JS jQuery

Symfony2 嵌入表单 : error not displayed

php - cakephp mysql 按查询分组

html - 如何在表单中提供切换按钮?

php - PhalconPHP Framework - 如何更新模型对象和相关对象

PHP $_POST 不工作?

php - 将动态生成的表单嵌入到另一个表单中

php - LiipImagineBundle 无法解析图像

php - 如何使用 HABTM 关系在 CakePHP 中查询数据?

php - 如何用PHP下载msg文件