Question

I´ve the following code to create a custom form type that transforms an entity to id in order to create an autocomplete field.

class EntityIdType extends AbstractType
{
    /**
     * @var EntityManager
     */
    private $em;

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

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $transformer = new EntityIdTransformer($this->em,$options['entity_class']);
        $builder->addModelTransformer($transformer);
    }
}

I have also created a custom widget to this form type and I want to get the string that represents that entity on it

{% block entity_id_widget %}
    {% spaceless %}
        <input type="hidden" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
        <input autocomplete="off" value="{{ **GET_VALUE_HERE** }}">
    {% endspaceless %}
{% endblock %}

UPDATE

The EntityIdTransformer's transform method just returns the entity's id and reverse transform returns the entity associated to the id passed as parameter

The goal of all this is to create an autocomplete input for an entity with many rows and persist the changes when submiting the form. If any other approach could be better for this example I will apreciate it.

It seems that an entity_identifier field type has been added as a proposal in a PR but doesnt seem to be available in near future yet

Was it helpful?

Solution

Finally I was able to get the string returning an array from the DataTransformer with an id and a string describing the entity

public function transform($entity)
{
    if (null === $entity) {
        return "";
    }

    return array("id" => $entity->getId(), "name" => $entity->__toString());
}

While rendering my custom widget now I can access to those values like this

{% block entity_id_widget %}
{% spaceless %}
    <input type="hidden" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value.id }}" {% endif %}/>
    <input class="blocked" autocomplete="off" {% if value is not empty %}value="{{ value.name }}" {% endif %}>
{% endspaceless %}
{% endblock %}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top