Symfony2数据转换器字符串到实体(reverseTransform)

时间:2018-01-13 07:10:33

标签: symfony symfony-2.8

我是Symfony的新手,希望有人能帮助我。我有一个名为Material的实体和一个名为MaterialKeyword的关联实体,它们基本上都是标签。我在表单上的文本字段中显示关键字逗号分隔为字符串。我创建了一个数据转换器来做到这一点。从数据库中提取关键字并显示它们没有问题,但是当我想将现有或新关键字提交到数据库时,我遇到了reversTransform函数的问题。

材质类(MaterialKeyword):

/**
 * @Assert\Type(type="AppBundle\Entity\MaterialKeyword")
 * @Assert\Valid()
 * @ORM\ManyToMany(targetEntity="MaterialKeyword", inversedBy="material")
 * @ORM\JoinTable(name="materials_keyword_map",
 *      joinColumns={@ORM\JoinColumn(name="materialID", referencedColumnName="materialID", nullable=false)},
 *      inverseJoinColumns={@ORM\JoinColumn(name="keywordID", referencedColumnName="id", nullable=false)})
 */
public $materialkeyword;


/**
* Constructor
*/
public function __construct()
{
    $this->MaterialKeyword = new ArrayCollection();
}


/**
 * Set materialkeyword
 *
 * @param array $materialkeyword
 *
 */
public function setMaterialkeyword(MaterialKeyword $materialkeyword=null)
{
    $this->materialkeyword = $materialkeyword;
}


/**
 * Get materialkeyword
 *
 * @Assert\Type("\array")
 * @return array
 */
public function getMaterialkeyword()
{
    return $this->materialkeyword;
}

这是我的数据转换器代码:

这部分正在运作:

class MaterialKeywordTransformer implements DataTransformerInterface
{
    /**
     * @var EntityManagerInterface
     */
    private $manager;


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

    /**
     * Transforms an object (materialkeyword) to a string.
     *
     * @param  MaterialKeyword|null $materialkeyword
     * @return string
     */
    public function transform($material)
    {
        $result = array();
        if (null === $material) {
            return '';
        }

        foreach ($material as $materialkeyword) {

            $result[] = $materialkeyword->getKeyword();
        }

        return implode(", ", $result);

    }

这部分不起作用:

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

    $repository = $this->manager
        ->getRepository('AppBundle:MaterialKeyword');


    $keyword_array = explode(", ", $keywords);

    foreach($keyword_array as $keyword){

        $materialkeyword = new MaterialKeyword();
        $keyword_entry = $repository->findBy(array('keyword' => $keyword));

        if(array_key_exists(0, $keyword_entry)){
            $keyword_entry_first = $keyword_entry[0];
        }else{
            $keyword_entry_first = $keyword_entry;
        }

        if (null === $keyword_entry_first) {
            throw new TransformationFailedException(sprintf('There is no "%s" exists',
                $keywords
            ));
        }
        $materialkeyword->setKeyword($keyword_entry_first);

    }


    return $materialkeyword;

}

会有几个关键字,所以我该如何存储它们。我尝试了Arrays和ArrayCollections(new ArrayCollection())但没有任何成功。

我目前使用上述代码获得的错误:

Catchable Fatal Error: Argument 1 passed to Doctrine\Common\Collections\ArrayCollection::__construct() must be of the type array, object given, called in /.../vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 605 and defined

3 个答案:

答案 0 :(得分:0)

根据您的说法,我假设MaterialMaterialKeyword由ManyToMany关联连接,在这种情况下,每个Material都有一个数组 MaterialKeyword个与之关联的对象。

这意味着,您的Data Transformer也应该使用数组,但您只能使用单个对象。

具体来说,reverseTransform应返回MaterialKeyword个对象的数组,而您只返回一个(循环中处理的最后一个)。

另一个问题是,您的方法每次都会创建新对象,即使$repository->findBy(...)已经返回MaterialKeyword实例。创建一个新对象会导致该条目被复制而不是简单地使用。

所以正确的方法可能如下所示:

public function reverseTransform($keywords)
{
    // no keyword? It's optional, so that's ok
    if (!$keywords) {
        return array();
    }

    $repository = $this->manager
        ->getRepository('AppBundle:MaterialKeyword');

    $keyword_array = explode(", ", $keywords);
    $result_list = array(); // This will contain the MaterialKeyword objects
    foreach($keyword_array as $keyword){
        $keyword_entry = $repository->findOneBy(array('keyword' => $keyword));

        if (null === $keyword_entry) {
            throw new TransformationFailedException(sprintf('There is no "%s" exists',
                $keyword
            ));
        }

        $result_list[] = $keyword_entry;
    }

    return $result_list;
}

答案 1 :(得分:0)

TL; DR; 您的reverseTransform函数应返回包含零或n MaterialKeyword的数组。

它不应该返回单个MaterialKeyword对象,因为MaterialKeyord[] --> string的反向转换不是string --> MaterialKeyword,而是string --> MaterialKeyword[]

考虑到这一点,你在尝试new ArrayCollection(/** Single MaterialKeyword object */)而不是new ArrayCollection(/** Array of MaterialKeyword objects */)时有意义的学说ArrayCollection异常。

答案 2 :(得分:0)

@Hanzi让我走上了正确的轨道。它必须是MaterialKeywords个对象的数组。

这是我在MaterialKeywordTransformer类中的最终工作代码:

    /**
     * Transforms a string (keyword) to an object (materialkeyword).
     *
     * @param  string $materialkeyword
     * @return MaterialKeyword|null
     * @throws TransformationFailedException if object (materialkeyword) is not found.
     */
    public function reverseTransform($keywords)
    {
         // keyword are optional, so that's ok
        if (!$keywords) {
            return;
        }

        $repository = $this->manager
            ->getRepository('AppBundle:MaterialKeyword');

        $repository_m = $this->manager
            ->getRepository('AppBundle:Material');

        $keyword_array = explode(", ", $keywords);

        foreach($keyword_array as $keyword){

            $materialkeyword = new MaterialKeyword();
            $materialkeyword->setKeyword($keyword);

            if($this->opt["data"]->getMaterialID() !== null) {
                $materialkeyword->setMaterialID($this->opt["data"]->getMaterialID());
            } else {
                $material = $repository_m->findOne();
                $materialID = $material[0]->getMaterialID();
                $materialkeyword->setMaterialID($materialID);
            }

            $materialkeywords[] = $materialkeyword;

            if (null === $keywords) {
                throw new TransformationFailedException(sprintf('There is no "%s" exists',
                    $keywords
                ));
            }

        }       

        return $materialkeywords;

    }