2

我正在尝试创建一个表单,允许经理批准休假请求列表(还计划有一个待办事项列表并希望能够将它们标记为已完成)。

我已多次阅读 [在同一页面上生成相同的表单类型多次 Symfony2(以及其他几个),我已经接近理解,但我对 Symfony 相当陌生,不清楚代码的哪些部分应该放在哪些文件中. 我在 Symfony3 with Doctrine 中使用表单类型和控制器。

我有从控制器中的查询($em->createQuery)返回的实体实例列表,我希望为每个实体实例生成一个表单,甚至为每个实体生成两个表单(一个用于批准,一个用于拒绝) .

引用的问题说您需要一个循环来显示和保存它们。我的意图是一次只处理(提交)一个。我假设这部分代码将进入控制器?

我正在为控制器使用 indexAction,但使用它更像是一个 Edit 操作,因为我将处理表单,所以我传入一个 Request 对象和对象作为参数。

>

class HRMgrController extends Controller
{
    /**
     * Lists all manager role requests and provide a means to approve/deny.
     *
     * @Route("/", name="hrmgr_index")
     * @Method({"GET", "POST"})
     * @Security("has_role('ROLE_APP_MANAGER')")
     */    
public function indexAction(Request $request, TimeOffRequest $timeOffRequest)
{
    if (!empty($timeOffRequest)) {
            $form = $this->createForm('CockpitBundle\Form\TORApprovalType', $timeOffRequest);
        print "TOR Id = " . $timeOffRequest->getId() . "<BR>";
        $em = $this->getDoctrine()->getManager();
        $form->handleRequest($request);
        print "Form name = " . $form->getName() . "<BR>";
        if ($form->isSubmitted() && $form->isValid()) {
            if ($form->get('approve')->isClicked()) {
                print "This puppy was approved";
                $timeOffRequest['status'] = 4;
            }
            if ($form->get('reject')->isClicked()) {
                print "This puppy was rejected";
                $timeOffRequest['status'] = 1;
            }
            $this->getDoctrine()->getManager()->flush();
            print "At least its there<BR>";
            // return $this->redirectToRoute('hrmgr_index');
        } else {
            print "did not detect form submission<BR>";
        }
    } 

    $emp = new \CockpitBundle\Entity\Employee();

    $date = new \DateTime();
    $year = $date->format('Y');
    $username = $this->getUser()->getUserName();
    $user = $em->getRepository('CockpitBundle:Employee')->findByUsername($username);
    $employees = $em->getRepository('CockpitBundle:Employee')->htmlContact($user);
    $tors = $em->getRepository('CockpitBundle:TimeOffRequest')->findMgrUnapprovedTORs($user->getId());
    $timeoff = "<h3>Unapproved Time Off Requests</h3>";
    $actions = true;

    $torforms = [];
    foreach ($tors as $tor) {
        $target = $this->generateUrl('hrmgr_index',array("tor_id" => $tor->getId()));
        $torforms[] = $this->actionForm($tor,$target)->createView();
    }
    return $this->render('hrmgr/index.html.twig', array(
        'torforms' => $torforms,
    ));

我现在可以使用表单但是当我提交它们时 isSubmitted() 似乎没有工作。它当前输出“未检测到表单提交”。

因此,当我有多个表单并提交一个时,handleRequest 是否得到正确的一个?我想我也可能在这里混淆了两个概念。我最近更改了代码以将 timeOffRequest 的 ID 作为参数提交给路由。它正确地选择了它,这使我可以更新表单,但那部分代码似乎不起作用。

我注意到,如果我查看调试器,我会得到如下信息:

>   approval_form_2 
   [▼
     "reject" => ""
     "_token" => "IE1rGa5c0vaJYk74_ncxgFsoDU7wWlkAAWWjLe3Jr1w"
   ]

如果我单击拒绝按钮。如果我单击批准按钮,我会得到一个带有“批准”的类似表格,所以看起来我很接近。此外,正确的 ID 会从操作中给出的路线中显示出来。

这是表单生成器:

<?php

namespace CockpitBundle\Form;


use CockpitBundle\Entity\Employee;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\ButtonType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class TORApprovalType extends AbstractType
{

    private $nameSuffix = null;
    private $name = 'time_req_approval';
    public function __constructor(string $suffix = null)   {
        //parent::__construct();

        $this->nameSuffix = $this->generateNameSuffix();
    }

    private function generateNameSuffix() {
        if ($this->nameSuffix == null ||  $this->nameSuffix == '') {
            $generator = new SecureRandom();
            //change data to alphanumeric string
            return bin2hex($generator->nextBytes(10));
        }

        return $this->nameSuffix;
    }
    public function setNameSuffix($suffix){
        $this->nameSuffix = $suffix;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // Build your form...
        $builder->add('approve', SubmitType::class, array(
            'label' => "Approve",
            'attr' => array("class"=>"action-approve"),
        ));
        $builder->add('reject', SubmitType::class, array(
            'label' => "Reject",
            'attr' => array("class"=>"action-reject"),
        ));
        //$builder->add('employee');

    }
    public function getName()    {
        if ($this->nameSuffix == null || $this->nameSuffix == "" ) {
            $this->nameSuffix = $this->generateNameSuffix();
        }
        return $this->name .'_'. $this->nameSuffix;
    }
    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'CockpitBundle\Entity\TimeOffRequest'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'cockpitbundle_timeoffrequest';
    }


}

有什么线索吗?(对不起,我正在度假,所以更新不是特别快。

4

2 回答 2

0

我能够让它与以下构建器一起工作。

   $builder->add('approve', SubmitType::class, array(
        'label' => "Approve",
        'attr' => array("class"=>"action-approve"),
    ));
    $builder->add('reject', SubmitType::class, array(
        'label' => "Reject",
        'attr' => array("class"=>"action-reject"),
    ));

然后在控制器表单中,我生成并处理表单。不确定这是否是最佳方式,但可以找到。当然,这种方法每次都会重绘整个列表,但这对我正在做的事情来说很好。

class HRMgrController extends Controller
{
    /**
     * Lists all manager role requests and provide a means to approve/deny.
     *
     * @Route("/", name="manager_home")
     * @Method({"GET"})
     * @Security("has_role('ROLE_APP_MANAGER')")
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();
        $emp = new \CockpitBundle\Entity\Employee();
        $employeeSummary = [];
        $date = new \DateTime();
        $year = $date->format('Y');
        $username = $this->getUser()->getUserName();
        $user = $em->getRepository('CockpitBundle:Employee')->findByUsername($username);
        $myemployees = $em->getRepository('CockpitBundle:Employee')->findManagersEmployees($user);
        $torRep = $em->getRepository('CockpitBundle:TimeOffRequest');
        $toas = [];
        $torforms = [];
        foreach ($myemployees as $employee) {
            $tors = $torRep->findAllMine($employee,$year);
            $toas[$employee->getDisplayName()] = $em->getRepository('CockpitBundle:TimeOffAllocation')->getEmpAllocation($employee->getId(),$year);
            $employeeSummary[$employee->getDisplayName()] = $torRep->mySummary($tors,$toas[$employee->getDisplayName()]);
            if (array_key_exists('items',$employeeSummary[$employee->getDisplayName()]['Vacation']['Requested'])) {
                foreach ($employeeSummary[$employee->getDisplayName()]['Vacation']['Requested']['items'] as $tor) {
                    $target = $this->generateUrl('hrmgr_tor_approval',array("tor_id" => $tor->getId()));
                    $torforms[] = $this->actionForm($tor,$target)->createView();
                }
            }
            if (array_key_exists('items',$employeeSummary[$employee->getDisplayName()]['Sick Time']['Requested'])) {
                foreach ($employeeSummary[$employee->getDisplayName()]['Sick Time']['Requested']['items'] as $tor) {
                    $target = $this->generateUrl('hrmgr_tor_approval',array("tor_id" => $tor->getId()));
                    $torforms[] = $this->actionForm($tor,$target)->createView();
                }
            }
            if (array_key_exists('Time Off',$employeeSummary[$employee->getDisplayName()]) && 
                    array_key_exists('items',$employeeSummary[$employee->getDisplayName()]['Time Off']['Requested'])) {
                foreach ($employeeSummary[$employee->getDisplayName()]['Time Off']['Requested']['items'] as $tor) {
                    $target = $this->generateUrl('hrmgr_tor_approval',array("tor_id" => $tor->getId()));
                    $torforms[] = $this->actionForm($tor,$target)->createView();
                }
            }
        }

        return $this->render('hrmgr/index.html.twig', array(
            'employeeSummary' => $employeeSummary,
            'torforms' => $torforms,
            'year' => $year,
        ));
    }
    /**
     * Lists all manager role requests and provide a means to approve/deny.
     *
     * @Route("/{tor_id}", name="hrmgr_tor_approval")
     * @Method({ "POST" })
     * @ParamConverter("timeOffRequest", class="CockpitBundle:TimeOffRequest", options={"id"="tor_id"})
     * @Security("has_role('ROLE_APP_MANAGER')")
     */
    public function approvalAction(Request $request, TimeOffRequest $timeOffRequest)
    {
        if (!empty($timeOffRequest)) {
            $form = $this->createForm('CockpitBundle\Form\TORApprovalType', $timeOffRequest);
            $id = $timeOffRequest->getId();
            $em = $this->getDoctrine()->getManager();
            $form->handleRequest($request);
            $postparams = $request->request->all();

            if (array_key_exists("approval_form_$id",$postparams)) {
                // Form was submitted
                if (array_key_exists("approve",$postparams["approval_form_$id"])) {
                    $status = $em->getReference('CockpitBundle\Entity\TimeOffStatus', 4);
                    $timeOffRequest->setStatus($status);
                    $timeOffRequest->setApprovedDate(new \DateTime);
                    $em->persist($timeOffRequest);
                    $em->flush($timeOffRequest);
                }
                if (array_key_exists("reject",$postparams["approval_form_$id"])) {
                    $status = $em->getReference('CockpitBundle\Entity\TimeOffStatus', 1);
                    $timeOffRequest->setStatus($status);
                    $timeOffRequest->setApprovedDate(new \DateTime);
                    $em->persist($timeOffRequest);
                    $em->flush($timeOffRequest);
                }
            } else {
                print "Form did not exist<BR>";
            }
            return $this->redirectToRoute('manager_home');
        } 
    }
    public function actionForm($tor,$target) {
        return $this->get('form.factory')->createNamedBuilder('approval_form_'.$tor->getId(), \CockpitBundle\Form\TORApprovalType::class, $tor,
             array("action"=> $target))->getForm();        
    }
}
于 2017-06-07T21:56:50.903 回答
0

您可以执行多个提交按钮:检查您的表单类型

    ->add('approve', 'submit')
    ->add('reject', 'submit')

然后在你的控制器中

 if ($form->isValid()) {
        // ... do something

        // the save_and_add button was clicked
        if ($form->get('approve')->isClicked()) {
            // probably redirect to the add page again
        }
        if ($form->get('reject')->isClicked()) {
            // probably redirect to the add page again
        }

        // redirect to the show page for the just submitted item
    }
于 2017-03-15T12:10:25.057 回答