简体   繁体   English

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

[英]Symfony2 (2.7) Form Entity Data Transformer

I'm trying to customize a selection list's text while using the entity's ID. 我试图在使用实体ID的同时自定义选择列表的文本。 This is because I want the list options to be specific to the authenticated user. 这是因为我希望列表选项特定于经过身份验证的用户。 The database text values are Full Name, By City and State, and Anonymous, but I want it to actually display the user's full name (John Smith), User in Denver, CO, and Anonymous. 数据库文本值为全名,按城市和州,以及匿名,但是我希望它实际显示用户的全名(约翰·史密斯),科罗拉多州丹佛市的用户和匿名。 I'm attempting to use a view data transformer to achieve this, but with no luck. 我正在尝试使用视图数据转换器来实现此目的,但是没有运气。 I'd rather not use Javascript to achieve this if possible. 如果可能,我宁愿不使用Javascript来实现这一目标。

Here's my main form type: 这是我的主要表单类型:

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

Here's my custom form type for Viewability (the entity which I would like to transform): 这是我针对可见度的自定义表单类型(我要转换的实体):

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

Here's my service which defines the Viewability Type: 这是我的服务,它定义了可见性类型:

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

Here's my Viewability Entity: 这是我的可见度实体:

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

Finally, here's my data transformer: 最后,这是我的数据转换器:

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

The data passed into transform() always seems to be null or "" (empty string). 传递到transform()的数据似乎总是为null或“”(空字符串)。

Thanks for any help. 谢谢你的帮助。

So I ended up taking a different approach to solving this. 因此,我最终采取了另一种方法来解决这个问题。 Originally I was trying to transform data coming from an entity. 最初,我试图转换来自实体的数据。 Fortunately this entity didn't really need to be a database entity after all and a simple choice type sufficed. 幸运的是,这个实体毕竟并不需要成为数据库实体,只需一个简单的选择类型即可。 This doesn't solve the specific issue of transforming an entity list, but it allows me to customize the drop down list values. 这不能解决转换实体列表的特定问题,但是可以让我自定义下拉列表值。

The viewability entity was removed and the relationship in the Message entity was changed to an integer field. 可见性实体已删除,并且消息实体中的关系更改为整数字段。

My main type is now as follows: 我的主要类型如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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