Symfony2(2.7)表单实体数据转换器

时间:2015-09-07 16:18:59

标签: forms symfony entity transformer

我正在尝试使用实体的ID自定义选择列表的文本。这是因为我希望列表选项特定于经过身份验证的用户。数据库文本值是全名,按城市和州,以及匿名,但我希望它实际显示用户的全名(John Smith),丹佛的用户,CO和匿名。我正在尝试使用视图数据转换器来实现这一点,但没有运气。如果可能的话,我宁愿不使用Javascript来实现这一点。

这是我的主要表单类型:

<?php

namespace Members\MessagesBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\SecurityContext;


class MessageType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('viewability', 'viewability_entity', array(
                'class' => 'MessagesBundle:Viewability',
                'property' => 'name',
                'required' => true,
            ))
            ->add('body', new MessageBodyType())
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Members\MessagesBundle\Entity\Message',
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'members_messages_message';
    }
}

这是Viewability的自定义表单类型(我想要转换的实体):

<?php

namespace Members\MessagesBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\SecurityContext;
use Members\MessagesBundle\Form\DataTransformer\MessageNameTransformer;


class ViewabilityType extends AbstractType
{
    private $context;

    /**
     * @param SecurityContext $context
     */
    public function __construct(SecurityContext $context)
    {
        $this->context = $context;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $transformer = new MessageNameTransformer($this->context);
        $builder->addViewTransformer($transformer);
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'invalid_message' => 'The selected issue does not exist',
        ));
    }

    /**
     * @return string
     */
    public function getParent()
    {
        return 'entity';
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'viewability_entity';
    }
}

这是我的服务,它定义了可见性类型:

members.messages.form.type.viewability_entity:
        class: Members\MessagesBundle\Form\ViewabilityType
        tags:
            - { name: form.type, alias: viewability_entity }
        arguments: [@security.context]

这是我的可见度实体:

<?php

namespace Members\MessagesBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity()
 */
class Viewability
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    public function __construct()
    {
    }

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param mixed $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param mixed $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }
}

最后,这是我的数据转换器:

<?php

namespace Members\MessagesBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Members\MessagesBundle\Entity\Viewability;
use Symfony\Component\Security\Core\SecurityContext;

class MessageNameTransformer implements DataTransformerInterface
{
    private $user;

    /**
     * @param SecurityContext $context
     */
    public function __construct(SecurityContext $context)
    {
        $this->user = $context->getToken()->getUser();
    }

    /**
     * @param Viewability|null $viewability
     * @return string
     */
    public function transform($viewability)
    {
        if (null === $viewability) {
            return '';
        }

        if($viewability === 'Full Name')
            return sprintf('%s %s', $this->user->getInfo()->getFirstName(), $this->user->getInfo()->getLastName());
        if($viewability === 2)
            return sprintf('Lawyer in %s,  %s', $this->user->getInfo()->getAddress()->getCity(), $this->user->getInfo()->getAddress()->getState());
        if($viewability === 3)
            return 'Anonymous';
    }

    /**
     * @param Viewability $viewability
     * @return Viewability
     */
    public function reverseTransform($viewability)
    {
        return $viewability;
    }
}

传递给transform()的数据似乎总是为null或“”(空字符串)。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

所以我最终采取了不同的方法来解决这个问题。最初我试图转换来自实体的数据。幸运的是,这个实体毕竟不需要是一个数据库实体,而且一个简单的选择类型就足够了。这不能解决转换实体列表的具体问题,但它允许我自定义下拉列表值。

删除了可见性实体,并将Message实体中的关系更改为整数字段。

我的主要类型现在如下:

class MessageType extends AbstractType
{
    private $user;

    public function __construct($user)
    {
        $this->user = $user;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('body', new MessageBodyType())
            ->add('viewability', 'choice', array(
                'choices'   => array(
                    1 => $user->getFirstName(),
                    2 => $user->getAddress()->getCity(),
                    3 => 'Anonymous',
                ),
                'multiple'  => false,
                'label'     => 'Send Message As',
                'data'      => 0,
            ))
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class'    => 'Members\MessagesBundle\Entity\Message',
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'members_messages_message';
    }
}