填充多个表单Symfony2

时间:2015-11-17 08:22:04

标签: php forms symfony formbuilder

我有一个控制器,我正在创建一个打开的工作列表,并通过Twig在表中填充它们。 我现在想要的是每行的最后一个字段是一个上传表单,以便您可以将文件添加到一个特定的作业。不幸的是,我不知道如何在一个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,但是如何分离表单句柄?

任何暗示都赞赏!

2 个答案:

答案 0 :(得分:1)

我将用你的法语后期逻辑来回答:

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

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

    foreach($jobs as $job) {


        $file = new File();
        $form = $this->get('form.factory')
                     ->createNameBuilder($job->getId(), new FileType(), $job)
                     ->getForm();


        $form->handleRequest($request);

        $forms[] = $form->createView();

        if ($form->isValid()) {

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

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

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

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

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


}

为了更清洁,创建一个单独的formType:

<?php
namespace AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class FileType extends AbstractType
{
    public function getName()
    {
        return 'my_file_type';
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
     $builder
        ->add('file')
        ->add('job','entity',array(
            'class' => 'AppBundle:Job',
            'choice_label' => 'insuranceDamageNo',
        ))
        ->add('save', 'submit', array('label' => 'Create Task'))
    }
}

答案 1 :(得分:1)

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

/**
 * @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;
}
相关问题