【问题标题】:Send single input from form type in symfony2从 symfony2 中的表单类型发送单个输入
【发布时间】:2015-10-27 22:57:07
【问题描述】:

我已经准备了自定义表单类型类 CheckListFormType。我那里有很多领域。

<?php

namespace AppBundle\Form\Type;

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

class CheckListType extends AbstractType{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('IMEI');
        $builder->add('serialNumber');
        $builder->add('visualCheck');
        $builder->add('callCheck');
        $builder->add('cameraCheck');
        $builder->add('checkMend');
        $builder->add('wifiCheck');
        $builder->add('wipeDataCheck');
        $builder->add('checkComment');
        $builder->add('checkDate');
        $builder->add('batch');
    }

    /**
     * Returns the name of this type.
     *
     * @return string The name of this type
     */
    public function getName()
    {
        return 'check_list';
    }
}

接下来,我在 Controller 中进行操作

public function updateCheckList(Request $request)
{
    $em = $this->getDoctrine()->getManager();

    $checkListId = $request->get('checkListId');
    $checkListRepository = $this->getDoctrine()->getRepository('AppBundle:CheckList');
    $checkList = $checkListRepository->find($checkListId);

    if(!$checkList){
        return new JsonResponse(array(
            'success' => false
        ));
    }

    $form = $this->createForm(new CheckListType(), $checkList);
    $form->handleRequest($request);

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


    return new JsonResponse(array(
       'success' => true
    ));
}

接下来我有很多关于这种表单类型的视图。在某些视图中,用户只能编辑“serialNumber”,而其他用户只能编辑“checkMend”等。

现在,当我从视图提交表单时,只有一个字段,学说会清除 CheckListEntity 中的所有其他属性。当我只提交一个输入时,如何避免清除其他字段。

【问题讨论】:

    标签: php forms symfony


    【解决方案1】:

    当您调用$form-&gt;handleRequest() 时,表单会将其所有值传递给实体。如果没有提交任何值,它将重置为默认值。如果您希望值保持原样,则必须从表单中删除该字段。

    您可以为每个案例单独定义表单,其中只包含可以修改的字段,或者您在现有表单上使用remove 方法来删​​除您希望在每个案例中保持不变的字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-18
      • 1970-01-01
      • 1970-01-01
      • 2013-02-24
      • 2012-07-08
      • 2021-05-09
      • 2016-03-08
      • 1970-01-01
      相关资源
      最近更新 更多