Symfony PUT不包含映射的所有实体属性

时间:2015-03-22 01:53:19

标签: php api symfony entity fosrestbundle

我正在使用FOSRestBundle来管理我的应用中的API。所以除了PUT方法之外我几乎所有工作都在工作,其中一些属性是NULL但是它们不应该是因为实体(id 105)已经填充它们。

看看putAction:

    /**
     * @ParamConverter("user", class="SoftwareBundle:User", options={"mapping": {"user": "guid"}})
     */
    public function putAction(Request $request, $user)
    {
        $form = $this->createForm(new UserType(), $user, ['method' => 'PUT']);
        $form->handleRequest($request);

        var_dump($user->getId()); // 105
        var_dump($user->getGuid()); // 12345
        var_dump($user->getEmailAddress()); // NULL (should be johndoe@example.com
        var_dump($user->getFirstName()); // NULL (should be John)
        var_dump($user->getLastName()); // NULL (should be Doe)
        var_dump($user->getSex()); // NULL (should be 0)
        var_dump($user->getPassword()); // pass123
        var_dump($user->getUserAgent()); // curl/7.30.0
        var_dump($user->getIpAddress()); // 127.0.0.1
        var_dump($user->getMember()->getPrivateNotes()); // example note

        if($form->isValid())
        {
            $manager = $this->getDoctrine()->getManager();
            $manager->flush();

            return $this->view([
                'user' => $user
            ]);
        }

        return $this->view($form, Codes::HTTP_BAD_REQUEST);
    }

问题是,为什么FirstName,LastName,EmailAddress和Sex为NULL?他们真的不应该。

以下是表单的外观:

class UserType extends AbstractFormType
{
    public function buildForm(FormBuilderInterface $builder, array $option)
    {
        $builder
            ->add('firstName', 'text', [
                'label' => 'word.first_name',
                'required' => true
            ])
            ->add('lastName', 'text', [
                'label' => 'word.last_name',
                'required' => true
            ])
            ->add('emailAddress', 'email', [
                'label' => 'word.email_address',
                'required' => true,
                'constraints' => [
                    new HasUsername($this->getOption('uuid'))
                ]
            ])
            ->add('sex', 'choice', [
                'label' => 'word.sex',
                'choices' => [
                    '0' => 'word.male',
                    '1' => 'word.female'
                ],
                'required'    => true,
                'empty_value' => 'word.select',
                'empty_data' => null
            ])
            ->add('locale', 'entity', [
                'label' => 'word.locale',
                'required'    => false,
                'property' => 'code',
                'class' => 'SoftwareBundle:Locale',
                'query_builder' => function(EntityRepository $er) {
                        return $er->createQueryBuilder('l')
                            ->orderBy('l.code', 'ASC');
                    },
                'placeholder' => 'word.select',
                'empty_data'  => null
            ])
            ->add('member', new MemberType(), [])
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults([
            'translation_domain'    => 'general',
            'data_class'            => 'Software\Bundle\Entity\User',
            'attr'                  => ['novalidate' => 'novalidate'],
            'csrf_protection'       => false
        ]);
    }

    public function getName()
    {
        return 'user';
    }

验证在单独的.yml文件中完成。

这是我发送动作的JSON:

{"user":{"member": {"privateNotes":"example note"}}}"

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

带有事件监听器的

I've solved it in past。诀窍是如果提交的值为null,则重写默认值:

namespace Acme\Bundle\UserBundle\Form;

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

class UserType extends AbstractType
{
    /**
     * @param FormBuilder $builder
     * @param array       $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email')
            ->add('name');

        $callback = function(FormEvent $event) {
            if (null === $event->getData()) {
                $event->setData($event->getForm()->getData());
            }
        };

        $builder->get('email')->addEventListener(FormEvents::PRE_SUBMIT, $callback);
        $builder->get('name')->addEventListener(FormEvents::PRE_SUBMIT, $callback);
    }

   // [ ... ]
}