genemu_jqueryautocompleter_entity with AJAX route_name setting JSON as value
webdevilopers opened this issue · 0 comments
webdevilopers commented
I use genemu_jqueryautocompleter_entity
inside the LexikFormFilterBundle:
$builder
->add('branch', 'genemu_jqueryautocompleter_entity', array(
'route_name' => 'ajax_branch',
'property' => 'name',
'class' => 'PlusquamContractBundle:Branch',
'required' => true
));
My AJAX Controller according to the route:
/**
* @Route("/branch/ajax", name="ajax_branch")
*/
public function ajaxAction(Request $request)
{
$value = $request->get('term');
$em = $this->getDoctrine()->getEntityManager();
$branches = $em->getRepository('AppBundle:Branch')
->findByName($value);
// Get branches by user if non-admin
$json = array();
foreach ($branches as $branch) {
$json[] = array(
'label' => sprintf('%s (%s)', $branch['name'], $branch['company_name']),
'value' => $branch['id']
);
}
$response = new Response();
// better way to return json - via header?
$response->setContent(json_encode($json));
return $response;
}
As suggested in:
A different JSON structure is mentioned here but does not work at all for the autocompleter:
http://stackoverflow.com/questions/22143219/want-to-use-genemu-formbundle-autocomplete-with-querybuilder
Generated Javascript:
jQuery(document).ready(function($) {
var $field = $('#integrator_contract_filter_branch');
var $autocompleter = $('#autocompleter_integrator_contract_filter_branch');
var $configs = {
focus: function(event, ui) {
return false;
},
select: function(event, ui) {
this.value = ui.item.label;
terms = ui.item;
$field.val(JSON.stringify(terms));
return false;
}
};
$configs.source = function(request, response) {
$.getJSON('/branch/ajax', {
term: request.term
}, response);
};
$autocompleter.autocomplete($configs);
});
When I select an entity my hidden input gets populated with the JSON array:
<label for="integrator_contract_filter_branch" class="required">Branch</label><input value="{"label":"Foo (Bar)","value":2}" id="integrator_contract_filter_branch" name="integrator_contract_filter[branch]" required="required" type="hidden"><span class="ui-helper-hidden-accessible" aria-live="polite" role="status">2</span><input autocomplete="off" class="ui-autocomplete-input" id="autocompleter_integrator_contract_filter_branch" name="autocompleter_integrator_contract_filter[branch]" required="required" type="text">
Shouldn't the javasript function populate the hidden input with the ID by default?
Possibly related: