Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering entity type as text field so I can auto-complete it with jquery

I've got Task entity which has nothing to do with Company entity ( Company has Projects, and each Project has Tasks ) and this simple form:

class TaskType extends AbstractType
{ 
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
       $builder->add('company','entity',array(
                'class' => 'ITMore\FlowBundle\Entity\Company',
                'mapped' => false
            ))
    }
}

and what I want to do is to render this field as text type, so I can auto-complete it with jquery ( friendly User experience. There will be a lot of projects, so I don't want user to search through the whole list ). It is supposed to work like this: user fill the company field, then the list of companies which fits input value shows and after that there is second input - project - which is supposed to have hints with the given companies projects.

I have absolutely no idea how to do this. One way which I thought it may work is to do this in controller after validation, but this solution isn't very neat

like image 663
mmmm Avatar asked Apr 07 '14 15:04

mmmm


2 Answers

Use 'entity' itself and use

http://ivaynberg.github.io/select2/

for implementing auto-complete.

like image 32
Ramesh Avatar answered Sep 26 '22 19:09

Ramesh


Use DataTransformer.

A working example.City entity has thousand of city names.Instead of dropdown, you can turn this into text input

<?php

namespace Project\Bundle\DuterteBundle\Form\DataTransformer;

use Project\Bundle\DuterteBundle\Entity\City;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;


class CityAutocompleteTransformer implements DataTransformerInterface
{
private $entityManager;

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

public function transform($city)
{
    if (null === $city) {
        return '';
    }

    return $city->getName();
}

public function reverseTransform($cityName)
{
    if (!$cityName) {
        return;
    }

    $city = $this->entityManager
        ->getRepository('DuterteBundle:City')->findOneBy(array('name' => $cityName));

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

    return $city;
}
}

Then in citytype form you can do similar this

->add('city', 'text', array(
        'label' => 'Type your city',
        //'error_bubbling' => true,
        'invalid_message' => 'That city you entered is not listed',

 $builder->get('city')
      ->addModelTransformer(new CityAutocompleteTransformer($this->entityManager));
like image 79
Danielle Rose Mabunga Avatar answered Sep 23 '22 19:09

Danielle Rose Mabunga