Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Quick auto-complete example
{# just render your form like normal #}
{# here is some example JavaScript #}
{# I'm using https://select2.github.io/ - it's version 3.5.2, so the below code will probably need to be updated for version 4! #}
<script type="text/javascript" src="{{ asset('assets/vendor/select2/select2.min.js') }}"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
$('.js-autocomplete-scientists').select2({
placeholder: "Search some scientists",
minimumInputLength: 1,
multiple: true,
ajax: {
url: '{{ path('api_genus_scientist') }}',
dataType: 'json',
data: function (term, page) {
return {
q: term, // search term
page: page
};
},
results: function (data, page) {
return {results: data.scientists};
}
},
initSelection: function(element, callback) {
// get an array of the ids
var ids = [];
$(element.val().split(",")).each(function () {
ids.push(this);
});
// send an AJAX to get the user information
$.ajax('{{ path('api_genus_scientist') }}', {
data: {
ids: ids
},
dataType: "json"
}).done(function(data) {
// pass the array of users to the callback to continue
callback(data.scientists);
});
},
formatResult: formatScientistResult,
formatSelection: formatScientistSelection
});
});
function formatScientistResult(scientist)
{
return '<div>'+scientist.username+'</div>';
}
function formatScientistSelection(scientist)
{
return scientist.username;
}
</script>
<?php
namespace Knp\UniversityBundle\Form\Type;
use Doctrine\Common\Persistence\ObjectManager;
use Knp\UniversityBundle\Form\DataTransformer\MultipleEntityToIdTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Based off of HiddenEntityType - for when you are selecting multiple items
*/
class HiddenMultipleEntityType extends AbstractType
{
/**
* @var ObjectManager
*/
private $om;
/**
* @param ObjectManager $om
*/
public function __construct(ObjectManager $om)
{
$this->om = $om;
}
/**
* Add the data transformer to the field setting the entity repository
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$entityTransformer = new $options['transformer']($this->om);
$entityTransformer->setEntityRepository($options['class']);
$builder->addModelTransformer($entityTransformer);
}
/**
* Require the entity repository option to be set on the field
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver
->setDefaults([
'transformer' => MultipleEntityToIdTransformer::class,
])
->setRequired([
'class',
])
;
}
/**
* A text field, but your widget should hide this
*/
public function getParent()
{
return TextType::class;
}
}
services:
hidden_multiple_entity_type:
class: Knp\UniversityBundle\Form\Type\HiddenMultipleEntityType
arguments:
- '@doctrine.orm.entity_manager'
tags:
- { name: form.type }
<?php
// inside the controller, create the API action for auto-complete
public function listJsonAction(Request $request)
{
$q = $request->query->get('q');
if ($q) {
$users = $this->getDoctrine()->getManager()
->getRepository('AppBundle:User')->searchByUsername($q);
} elseif ($ids = $request->query->get('ids')) {
$users = $this->getDoctrine()->getManager()
->getRepository('AppBundle:User')->findByIds($ids);
} else {
throw new BadRequestHttpException('Invalid filtering parameters');
}
$data = array('scientists' => array());
foreach ($users as $user) {
$data['scientists'][] = array(
'id' => $user->getId(),
'username' => $user->getUsername(),
);
}
return new JsonResponse($data);
}
// inside buildForm()
$builder
->add('authors', HiddenMultipleEntityType::class, array(
'class' => 'AppBundle:User',
'attr' => ['class' => 'js-autocomplete-scientists']
))
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.