Skip to content

Instantly share code, notes, and snippets.

@ksn135
Last active October 26, 2015 12:37
Show Gist options
  • Save ksn135/447dfbf674f16b1e8e94 to your computer and use it in GitHub Desktop.
Save ksn135/447dfbf674f16b1e8e94 to your computer and use it in GitHub Desktop.
Symfony2Admingenerator Select2 ajax mode
<?php
namespace Ksn135\CompanyBundle\Controller\Employee;
use Admingenerated\Ksn135CompanyBundle\BaseEmployeeController\ActionsController as BaseActionsController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
* ActionsController
*/
class ActionsController extends BaseActionsController
{
public function ajaxAction(Request $request, $id = null)
{
try {
$manager = $this->getDoctrine()->getManager();
$results = $manager->getRepository('Ksn135CompanyBundle:Employee')
->getResultsForAjax($id, $request->request->get('q'));
$serialized = $this->container->get('serializer')->serialize($results, 'json');
return new JsonResponse([
'success' => true,
'results' => json_decode($serialized),
]);
} catch (\Exception $exception) {
return new JsonResponse([
'success' => false,
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
]);
}
}
}
employee:
filterable: true
label: Employee
filterType: s2a_select2_entity
formType: s2a_select2_entity
addFormOptions:
hidden: true
configs:
placeholder: Please, choose an employee
allowClear: true
minimumInputLength: 3
ajax:
type: 'POST'
url: 'function() { return Routing.generate("ajax_get_employees"); }'
dataType: 'json'
quietMillis: 250
data: 'function (term, page) { return { q: term }; }'
results: 'function (data, page) { return { results: data.results }; }'
cache: true
initSelection: 'function(element, callback) { var id = $(element).val(); if (id !== "") { $.ajax(Routing.generate("ajax_get_employee", {id: id}), { type: "POST", dataType: "json" }).done(function(data) { callback(data.results[0]); });}}'
<?php
use JMS\Serializer\Annotation as JMS;
/**
* @JMS\ExclusionPolicy("all")
*/
class Employee extends BaseUser
{
/**
* @JMS\Expose()
*/
protected $id;
/**
* @JMS\Expose()
* @JMS\SerializedName("text")
*/
private $fullName;
}
# put it into app/serializer/FOSUB/Model.User.yml
FOS\UserBundle\Model\User:
exclusion_policy: ALL
ajax_get_employees:
pattern: /ajax/get/employees
defaults:
_controller: Ksn135CompanyBundle:Employee/Actions:ajax
methods: [POST]
options:
expose: true
ajax_get_employee:
pattern: /ajax/get/employee/{id}
defaults:
id: ~
_controller: Ksn135CompanyBundle:Employee/Actions:ajax
_format: json
methods: [POST]
options:
expose: true
@nicoip
Copy link

nicoip commented Oct 26, 2015

Hello,

Can you show the function : getResultsForAjax() please?

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment