0

В Admin классе создаю поле:

$formMapper->add('mapped_field_name', ChoiceFieldMaskType::class, $options);

mapped_field_name - ассоциация многие-ко-многим

В $options все стандартно, по мануалу, задаются ['choices'] и ['map'].

На этапе добавления и просмотра все работает прекрасно: в БД добавляется, на странице просмотра все значения отображаются соответственно хорошо.

Когда открываю форму редактирования, то случается exception:

Unable to transform value for property path "mapped_field_name": Expected an array.

Кто сталкивался, как решали?

1 ответ 1

0

Нужно создать Transformer для такого свойства, и подключить его при создании формы в Admin-классе:

 <?php

namespace AppBundle\Form\DataTransformer;

use AppBundle\Repository\ClientFieldOptionRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\PersistentCollection;
use Symfony\Component\Form\DataTransformerInterface;

/**
 * Class AdditionalFieldToArrayTransformer
 * @package AppBundle\Form\DataTransformer
 */
class AdditionalFieldToArrayTransformer implements DataTransformerInterface
{

    /** @var  ClientFieldOptionRepository */
    private $clientFieldOptionRepository;

    /**
     * AdditionalFieldToArrayTransformer constructor.
     * @param ClientFieldOptionRepository $clientFieldEntityRepository
     */
    public function __construct(ClientFieldOptionRepository $clientFieldEntityRepository)
    {
        $this->clientFieldOptionRepository = $clientFieldEntityRepository;
    }

    /**
     * @param mixed $value
     * @return null
     */
    public function transform($value)
    {
        if(null === $value){
            return $value;
        }

        $result = null;

        if($value instanceof PersistentCollection){
            foreach ($value as $item) {
                $result[$item->getName()] = $item->getId();
            }
        } else {
            $result = $value->getId();
        }

        return $result;
    }

    /**
     * @param mixed $value
     * @return null|object
     */
    public function reverseTransform($value)
    {
        $result = null;

        if(null === $value){
            return $result;
        } else {
            if(is_array($value)){
                $newResult = new ArrayCollection();
                $result = $this->clientFieldOptionRepository->findBy(['id' => $value]);
                foreach ($result as $item){
                    $newResult->add($item);
                }
                $result = $newResult;

            } else {
                $result = $this->clientFieldOptionRepository->find($value);
            }

            return $result;
        }

    }
}

Регистрируем трансформер, как сервис, если нужно, в данном случае - да, он имеет зависимости:

  app.additional_field_to_array.transformer:
    class: AppBundle\Form\DataTransformer\AdditionalFieldToArrayTransformer
    arguments: ['@app.client_field_option.repository']

И пользуемся:

$transformer = $this->getConfigurationPool()->getContainer()->get('app.additional_field_to_array.transformer');
$formMapper->getFormBuilder()->get('mapped_field_name')->addModelTransformer($transformer);

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.