2

我尝试使用具有自动完成功能的野外城市。我使用 twitter bootstrap 样式和函数 typeahead,但我不知道我的工作是否好。

在我的示例中,我有 2 个实体:Person 和 City(法国约有 37,000 个公社)。

Person 实体与 City 字段 Birthplace 具有 OneToMany 关系。

因此,我创建了一个隐藏字段类型 city_typeahead 来添加一个 DataTransformer“CityToIdTransformer”,以从表单发送的 City id 中持久化一个对象。

在那之前,自动完成功能非常适合创建和编辑。

但是,在编辑表单中,我想在自动完成字段中显示在我的隐藏字段中注册的城市名称。这就是我卡住的地方。

我想与听众一起尝试,但我不确定要应用的解决方案。如果有人可以指导我,我将不胜感激。

谢谢你。

编辑: 我对自动完成字段国家进行了类似的测试,经过几次测试后我到达了。我创建了一个侦听器来检查隐藏字段是否有值,并从中获取名称并加载我的字段自动完成。我不知道该方法是否干净,但它有效,我的自动完成字段现在在编辑表单上显示国家名称。

表单类型:

<?php

namespace Myapp\PersonBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

use Myapp\PersonBundle\Form\EventListener\AddNationalitySearchSubscriber;

class PersonType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {       
        $builder
            ->add('firstname')
            ->add('lastname')                
            ->add('nationality', 'country_typeahead', array(
                'attr' => array('class' => 'country-toset'),
                'required' => false))
            ->add('nationality_search','text', array(
            'attr' => array(
                'class' => 'country-tosearch',
                'name' => 'term',
                'autocomplete' => true,
            'required' => false,
            'mapped' => false));   

        $builder->addEventSubscriber(new AddNationalitySearchSubscriber());   
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Myapp\PersonBundle\Entity\Person'
        ));
    }

    public function getName()
    {
        return 'person_person_type';
    }
}

视图中的脚本js:

<script type="text/javascript"> 
            $('.country-tosearch').typeahead({
                source: function(query, process){ 
                    $.ajax({
                        url: "/ajax/country",
                        type: "post",
                        data: "term="+query,
                        dataType: "json",
                        async: false,
                        success: function(data){                            
                            countries = []
                            mapped = {}                            
                            $.map(data, function(country, i){
                                mapped[country.name] = country;
                                countries.push(country.name);
                            });
                            process(countries);
                        }
                    })
                },
                minLength: 3,
                property: 'enriched',
                items:15,
                updater: function (obj) {
                    if(mapped[obj].id){
                        $('.country-toset').val(mapped[obj].id);
                    }
                    return mapped[obj].name;
                }
            });            
        </script>

数据转换器:

<?php 
namespace Myapp\PersonBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Doctrine\Common\Persistence\ObjectManager;

use Myapp\GeoBundle\Entity\Country;

class CountryToIdTransformer implements DataTransformerInterface
{
    /**
     * @var ObjectManager
     */
    private $om;

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

    /**
     * Transforms an object (country) to a string (id).
     *
     * @param  Country|null $country
     * @return string
     */
    public function transform($country)
    {
        if (null === $country) {
            return "";
        }

        return $country->getId();
    }

    /**
     * Transforms a string (id) to an object (country).
     *
     * @param  string $id
     * @return Country|null
     * @throws TransformationFailedException if object (country) is not found.
     */
    public function reverseTransform($id)
    {
        if (!$id) {
            return null;
        }

        $country = $this->om
            ->getRepository('MyappGeoBundle:Country')->findOneBy(array('id' => $id))
        ;

        if (null === $country) {
            throw new TransformationFailedException(sprintf(
                'A country with id "%s" does not exist!',
                $id
            ));
        }

        return $country;
    }
}

听众:

<?php

namespace Myapp\PersonBundle\Form\EventListener;

use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class AddNationalitySearchSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(FormEvents::PRE_SET_DATA => 'preSetData');
    }

    public function preSetData(FormEvent $event)
    {
        $country = '';
        $data = $event->getData();
        $form = $event->getForm();

        if (null === $data) {
            return;            
        }

        if ($data->getNationality()) {
            $country = $data->getNationality();
        }

       $form->add('nationality_search','text', array(
            'attr' => array(
                'class' => 'country-tosearch',
                'name' => 'term',
                'autocomplete' => true,
            'data' => $country,
            'required' => false,
            'mapped' => false));   
    }
}
4

0 回答 0