开发者

How to work with entity form field type, and JUI autocomplete in Symfony2?

开发者 https://www.devze.com 2023-04-11 21:10 出处:网络
I have form where I have entity field type, witch enables user to choose the related Client entity. It works great in dev environment but in production there will be thousands of clients to choose fro

I have form where I have entity field type, witch enables user to choose the related Client entity. It works great in dev environment but in production there will be thousands of clients to choose from, and HTML form field types will not be able to handle this.

I've wri开发者_JS百科tten action witch uses Zend Lucene and returns clients in JSON format for JUI autocomplete, how I can enable this autocomplete with entity form field type?


This is not exactly the answer you want, cause I did it with a choice field, and it's kind of a work around. This is a form where you can select receivers for sending a message(=campaign):

In the FormType:

    public function __construct(EntityManager $em, Campaign $campaign) {
        $this->campaign = $campaign;
        $this->em = $em;
    }

    public function buildForm(FormBuilder $builder, array $options)
    {
        $contactChoices = array('0'=>'');
        if($this->campaign && $this->campaign->getRecipientContacts()){
            foreach($this->campaign->getRecipientContacts() as $contact){
                $contactChoices[$contact->getHash()] = $contact->getName();
            }
        }
        $builder->add('subject')
                ->add('message','textarea')
                ->add('recipientContacts','choice', array(
                        'required' => false,
                        'multiple' => true, // manage multiple choices
                        'choices' => $contactChoices,
                        'property_path' => false,
                    ))
                ...

Then in the controller: retrieve the posted contacts and assign them to the campaign:

       if($this->getRequest()->getMethod() == 'POST'){
            $campaign->removeRecipientContacts();
            $data = $this->getRequest()->get('campaignForm');

            if(isset($data['recipientContacts'])){
                foreach($data['recipientContacts'] as $hash){
                   $contact = $this->getRepo()->getContactByHash($hash);
                   $campaign->addRecipientContact($contact);
                }
            }
        }

This allows you to use whatever JS widget (autocomplete,...) on the frontend. Simply add options to your choice field. Kind of:

function addContact(hash,name){
     $('#campaignContactChoiceSelectField').append('<option value="'+hash+'">'+name+'</option>');
}
0

精彩评论

暂无评论...
验证码 换一张
取 消