donglu5235 2017-06-07 12:06
浏览 45
已采纳

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

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. Usually they are hidden because only 1 type of user can access them - ROLE_ADMIN and the rest is for ROLE_EDITOR. In my case the ADMIN needs to only approve or reject it and the EDITOR can't do that. 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. 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

  <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 -

/** @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. Is there a way to say $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. So far when one of the buttons - "Approve" or "Reject" is clicked in the "edit" action $edit_form->IsSubmited() returns false.

  • 写回答

1条回答 默认 最新

  • duan0065626385 2017-06-07 13:16
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵