默认情况下显示自动填充字段中的名称,其ID在隐藏字段中

时间:2013-03-12 18:32:21

标签: forms symfony autocomplete

我尝试使用自动填充的字段城市。我使用twitter bootstrap风格和函数类型,但我不知道我的工作是否合适。

在我的例子中,我有两个实体:人和城市(约有37,000个法国公社)。

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

所以我创建一个隐藏字段类型city_typeahead来添加一个DataTransformer“CityToIdTransformer”来保存表单发送的City id中的对象。

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

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

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

谢谢。

编辑: 我使用自动填充字段国家进行了类似的测试,经过多次测试后我才到达。 我创建了一个监听器,检查隐藏字段是否有值,并从中获取名称并加载我的字段自动完成。 我不知道该方法是否干净,但它确实有效,我的自动填充字段现在会在编辑表单中显示该国家/地区的名称。

FormType:

<?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>

DataTransformer:

<?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));   
    }
}

0 个答案:

没有答案