【问题标题】:Symfony2 datatransformer cannot transformSymfony2 数据转换器无法转换
【发布时间】:2015-12-02 17:03:05
【问题描述】:

大家好,我正在尝试制作具有对象隐藏字段(正在构建)的 FloorType 表单,并且我无法使用食谱中的转换代码转换对象实体。

http://symfony.com/doc/2.7/cookbook/form/data_transformers.html

代码如下:

变压器

namespace George\FloorBundle\Form\DataTransformer;

use  George\ObjectsBundle\Entity\Object;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

class ObjectToNumberTransformer implements DataTransformerInterface
{
private $manager;

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

/**
 * Transforms an object (issue) to a string (number).
 *
 * @param  Object|null $issue
 * @return string
 */
public function transform($object)
{
    if (null === $object) {
        return '';
    }

    return $object->getId();
}

/**
 * Transforms a string (number) to an object (issue).
 *
 * @return Object|null
 * @throws TransformationFailedException if object (issue) is not found.
 */
public function reverseTransform($objectNumber)
{
    // no issue number? It's optional, so that's ok
    if (!$objectNumber) {
        return;
    }

    $object= $this->manager
        ->getRepository('ObjectsBundle:Object')
        // query for the issue with this id
        ->find($objectNumber)
    ;

    if (null === $object) {
        // causes a validation error
        // this message is not shown to the user
        // see the invalid_message option
        throw new TransformationFailedException(sprintf(
            'An issue with number "%s" does not exist!',
            $objectNumber
        ));
    }

    return $object;
}
}

楼层类型

namespace George\FloorBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use George\FloorBundle\Form\DataTransformer\ObjectToNumberTransformer;
use Doctrine\Common\Persistence\ObjectManager;

class FloorType extends AbstractType
{
private $manager;

public function __construct(ObjectManager $manager)
{
    $this->manager = $manager;
}
/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{

    $builder
        ->add('translations', 'a2lix_translations',array(
            'required_locales' => array('bg','en')
        ))
    ->add('object')->addModelTransformer(new ObjectToNumberTransformer($this->manager));
}

/**
 * @param OptionsResolverInterface $resolver
 */
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'George\FloorBundle\Entity\Floor'
    ));
}

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

创建CreteForm

private function createCreateForm(Floor $entity)
{
    $manager = $this->getDoctrine()->getManager();
    $form = $this->createForm(new FloorType($manager), $entity, array(
        'action' => $this->generateUrl('admin_floor_create'),
        'method' => 'POST',
    ));

    $form->add('submit', 'submit', array('label' => 'Create'));

    return $form;
}

服务

 <services>
    <service id="app.form.type.task" class="George\FloorBundle\Form\FloorType">
        <tag name="form.type" />
        <argument type="service" id="doctrine.orm.entity_manager"></argument>
    </service>
</services>

而且最大的错误是:

Catchable Fatal Error: Object of class George\ObjectsBundle\Entity\Object could not be converted to string 

有趣的是,服务不起作用,我需要将创建表单放入经理:

$manager = $this->getDoctrine()->getManager();

所以我知道变压器发生故障,但我看不到在哪里......有人可以帮助我进行这个转换吗?

【问题讨论】:

    标签: symfony service entity formbuilder


    【解决方案1】:

    你的语法有点不对劲。 $builder->add 实际上返回一个构建器对象,而不是添加的表单对象。书中显示:

    $builder->add(
      $builder->create('description', 'textarea')
        ->addModelTransformer(...)
    );
    

    在你的情况下,它会是这样的:

    $builder
      ->add('translations', 'a2lix_translations',array(
            'required_locales' => array('bg','en')
      ))
      ->add(
        $builder->create('object','text')
          ->addModelTransformer(new ObjectToNumberTransformer($this->manager))
      ));
    

    可能有括号搞砸了,但你明白了。

    【讨论】:

    • 不,不是这个......现在一切正常我不明白这是什么......
    • 它可能看起来有效,但除非您使用上述语法,否则模型转换器应用不正确。如果添加了另一个字段,或者顺序更改或出现月食,您可能会遇到麻烦。相信文档。
    【解决方案2】:

    你应该使用这个

    $builder
        ->add('translations', 'a2lix_translations',array(
            'required_locales' => array('bg','en')
        ))
    ->add('object');
    $builder->get('object')->addModelTransformer(new ObjectToNumberTransformer($this->manager));
    

    而不是

    $builder
            ->add('translations', 'a2lix_translations',array(
                'required_locales' => array('bg','en')
            ))
            ->add('object')->addModelTransformer(new ObjectToNumberTransformer($this->manager));
    

    希望对你有帮助!!

    【讨论】:

      【解决方案3】:

      关于第二个问题的解决方案是在服务中使用别名:

      <services>
          <service id="app.form.type.floor" class="George\FloorBundle\Form\FloorType">
              <tag name="form.type" alias="george_floorbundle_floor" />
              <argument type="service" id="doctrine.orm.entity_manager"></argument>
          </service>
      </services>
      

      我在哪里创建表单:

       $form = $this->createForm('george_floorbundle_floor', $entity, array(
          'action' => $this->generateUrl('admin_floor_update', array('id' => $entity->getId())),
          'method' => 'PUT',
         ));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-03
        • 2013-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-19
        相关资源
        最近更新 更多