简体   繁体   中英

Send single input from form type in symfony2

I have prepared custom form type class CheckListFormType. I have many fields there.

<?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';
    }
}

Next, I have action in 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
    ));
}

Next I have many views with this form type. In some view user can only edit 'serialNumber' in other user can edit only 'checkMend' etc.

Now when I submit form from view, where is only one field, doctrine clears all other properties from CheckListEntity. How can I avoid of clearing other fields, when I submit only one input.

When you call $form->handleRequest() the form passes all its values to the entity. If no value has been submitted, it will reset it to the default value. If you want the value to be left as it is, you have to remove that field from the form.

You can either define the forms separately for each case containing just the fields that can be modified, or you use the remove method on your existing form to get rid of the fields you want to be left untouched in each case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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