简体   繁体   English

Symfony3更改控制器中的表单字段类型

[英]Symfony3 change form field type in the controller

I have a form builder which builds a form 我有一个生成表单的表单生成器

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->
        add('typeTask',TextType::class,array('label'=>"Вид заявка"))->
        add('description',TextareaType::class,array('label'=>"Описание"))->
        add('term',DateType::class, array(
            'widget' => 'choice',
            'label'=>"Краен срок"
        ))->
        add('designer',TextareaType::class,array('label'=>"Дизайнер",
            "required"=>false))->
        add('executioner',TextareaType::class,array('label'=>"Под изпълнител",
            "required"=>false))->
        add("file",TextType::class,array('label'=>"Файл",
            "required"=>false))->
        add("ergent",CheckboxType::class,array('label'=>"Спешно",
            "required"=>false))->add("approved",HiddenType::class,array(
            "required"=>false
        ))->add("rejected",HiddenType::class,array(
            'required'=>false
        ));
    }

As you see I have 2 fields which are "approved" which can be true or false and rejected which can also be true and false. 如您所见,我有2个字段为“已批准”,可以为真或假,被拒绝的字段也可以为真和假。 Usually they are hidden because only 1 type of user can access them - ROLE_ADMIN and the rest is for ROLE_EDITOR. 通常它们是隐藏的,因为只有一种类型的用户可以访问它们-ROLE_ADMIN,其余的用于ROLE_EDITOR。 In my case the ADMIN needs to only approve or reject it and the EDITOR can't do that. 就我而言,ADMIN只需要批准或拒绝它,而编辑者就不能这样做。 The biggest issue is that I don't need a whole form, but rather 2 buttons - "Approve" and "Reject" when the Project is shown ("show" action), but the action which changes the Project is "edit" and so what I tried so far is from "show" to send a form to "edit" and then when the edit action is over to load the "show" action again.I tried achieving this by creating 2 forms - approveForm and rejectForm which can hold only 1 property each and send and flush them to "edit" function, but the edit function doesn't accept the form and also if it did it would have deleted everything else. 最大的问题是,我不需要一个完整的表单,而是两个按钮-显示项目时“批准”和“拒绝”(“显示”操作),但是更改项目的操作是“编辑”和所以到目前为止,我尝试的是从“显示”将表单发送到“编辑”,然后在编辑操作结束后再次加载“显示”操作。我尝试通过创建2个表单来实现此approveFormrejectForm每个仅拥有1个属性,然后将其发送并刷新到“ edit”函数,但是edit函数不接受该表单,并且如果这样做,它将删除所有其他内容。 Here is my code so far 到目前为止,这是我的代码

In show action - 在表演动作中-

$projectFormApprove = $this->createForm('AppBundle\Form\ProjectType', $project,array(
            "method"=>"post"
        ));
        $projectFormApprove->remove("description");
        $projectFormApprove->remove("designer");
        $projectFormApprove->remove("executioner");
        $projectFormApprove->remove("term");
        $projectFormApprove->remove("typeTask");
        $projectFormApprove->remove("file");
        $projectFormApprove->remove("ergent");
        $projectFormApprove->remove("approved");
        $projectFormApprove->remove("rejected");
        $projectFormApprove->add("approved",HiddenType::class,array(
            "data"=>true
        ));
        $projectFormReject = $projectFormApprove;
        $projectFormReject->remove("approved");
        $projectFormReject->add("rejected",HiddenType::class,array(
            'data'=>true
        )); 

This will create 2 forms each having 1 property and here is what happens in my twig template 这将创建2个表单,每个表单具有1个属性,这是我的树枝模板中发生的情况

  <tr>
        <td>
           {{ form_start(approveForm, {'action': path('project_edit', { 'id': project.id })}) }}
           {{ form_widget(approveForm) }}
               <input type="submit" value="Approve" />
           {{ form_end(approveForm) }}
        </td>
   </tr>
   <tr>
       <td>
        {{ form_start(rejectedForm,{'action': path('project_edit', { 'id': project.id })}) }}
               {{ form_widget(rejectedForm) }}
                 <input type="submit" value="Reject" />
               {{ form_end(rejectedForm) }}
           </td>
       </tr>

I need two forms since there are 2 buttons which simply submit them and no one actually changes the value ( this is the reason why in "show" function the created property have "data"=>true . If the form is submitted it will do it automatically. Here is what is in my "edit" function - 我需要两个表单,因为有两个按钮可以简单地提交它们,而实际上没有人更改值(这就是为什么在“显示”功能中,创建的属性具有"data"=>true 。如果提交了表单,它将执行它是自动的。这是我的“编辑”功能中的内容-

/** @var  $user User */
        $user = $this->getUser();
        $project = new Project();
        $form = $this->createForm('AppBundle\Form\ProjectType', $project);
        if($user->getType() != "LittleBoss"){
            $form->remove("designer");
            $form->remove("executioner");
        }
        $form->handleRequest($request);


        if ($form->isSubmitted() && $form->isValid()) {
        $project->setFromUser($user->getUsername());
        $project->setDepartment($user->getDepartment());
        $project->setIsOver(false);
        $project->setDate(new \DateTime());
        $project->setSeenByDesigner(false);
        $project->setSeenByExecutioner(false);
        $project->setSeenByLittleBoss(false);
        $project->setSeenByManager(false);
            $em = $this->getDoctrine()->getManager();
            $em->persist($project);
            $em->flush();

            return $this->redirectToRoute('project_show', array('id' => $project->getId()));
        }

        return $this->render('project/new.html.twig', array(
            'project' => $project,
            'form' => $form->createView(),
        ));

Now to my actual problem - As you see I first remove "approved" field and then I add new one with predefined value. 现在是我的实际问题-如您所见,我首先删除“已批准”字段,然后添加具有预定义值的新字段。 What I want is to change not the values, but the type of description and the rest fields. 我要更改的不是值,而是description的类型和其余字段。 Is there a way to say $form->change(); 有没有办法说$form->change(); or anything that can change the types of the fields without having to remove them. 或无需删除即可更改字段类型的任何内容。 The type I want them to be is HiddenType and set their data so that when I submit one of the 2 forms it will be accepted as valid in the "edit" action then flushed to the database and everything will be fine. 我希望他们的类型是HiddenType并设置他们的数据,这样当我提交2个表单之一时,它将在“编辑”操作中被接受为有效表单,然后刷新到数据库,一切都会好起来。 So far when one of the buttons - "Approve" or "Reject" is clicked in the "edit" action $edit_form->IsSubmited() returns false. 到目前为止,在“编辑”操作中单击按钮“批准”或“拒绝”之一时, $edit_form->IsSubmited()返回false。

I suggest you to create seperate forms, one for editor and another for admin. 我建议您创建单独的表单,一个用于编辑器,另一个用于管理员。 Then in controller use the form you need by permissions of the logged in user. 然后在控制器中,通过登录用户的权限使用您需要的表格。

if ($this->authorizationChecker->isGranted('ROLE_EDITOR')) {
     $form = $this->createForm(EditorType::class);
} elseif ($this->authorizationChecker->isGranted('ROLE_ADMIN')) {
     $form = $this->createForm(AdminType::class);
}

$form->handleRequest($request);

In both forms you can use same entity, but different fields. 在这两种形式中,您可以使用相同的实体,但可以使用不同的字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM