I am working on a Symfony project where I have a product entity and I need an Ajax search bar to search for through my products and select some of them. The problem is I have a search bar which gives me live results from the database but if I select the product it should show the data in my table. For some reason I am not able to show the selected results in my table.
js
$('.js-data-example-ajax').select2({
ajax: {
url: '/product/api/search',
dataType: 'json',
}
});
Controller
public function viewActionSearch(Request $request)
{
$query = $request->get('term');
$result = [
'results' => [],
];
if ($query !== null){
$products = $this->productRepository->getSearchList($query);
$result['results'];
foreach ($products as $product) {
$result['results'][] = [
'id' => $product['id'],
'text' => $product['name'],
];
}
} else {
$products = $this->productRepository->getResultList(1);
foreach ($products as $entity) {
$result['results'][] = [
'id' => $entity['id'],
'text' => $entity['name'],
];
}
}
return new JsonResponse($result);
}
ProductList
public function getPage(Request $request)
{
$products = $this->productRepository->getAllProducts($currentPage);
return $this->render(
'#app_bar/Product/productList.twig',
[
'products' => $products,
]
);
}
Twig
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<!-- select2 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/gh/ttskch/select2-bootstrap4-theme#master/dist/select2-bootstrap4.min.css" rel="stylesheet">
<div class="container mt-5">
<form>
<div class="form-group">
<select class="js-data-example-ajax form-control"></select>
</select>
</div>
</form>
</div>
<table class="table table-hover table-responsive">
<thead>
<tr>
<th>id</th>
<th>Title</th>
<th>SKU</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for product in products %}
<tr>
<td>
{{ product.id }}
</td>
<td>
{{ product.name }}
</td>
<td>
{{ product.sku }}
</td>
<td>
<a href="{{ path('app_product_getproduct', {'id': product.id}) }}" class="btn btn-success btn-sm" >
<span class="glyphicon glyphicon-pencil"></span>
</a>
<a href="{{ path('app_product_delete', {'id': product.id}) }}" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure?')">
<span class="glyphicon glyphicon-trash"></span>
</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
If I visit the route /product/api/search/ it's giving my a result back but i am not able to show these selected products in my table.
You missing something here. Symfony does not work like frontend frameworks like vue.js or similar. What you are doing you are rendering serverside request and after that, you just fetch data via AJAX and you do nothing with that data. jQuery needs instructions on what to do with data you get from the server. You can always use Symfony alongside some frontend framework, but you need to understand the difference when serverside renders your twig template and when frontend framework renders it.
http://api.jquery.com/jquery.ajax/
Hint:
$('.js-data-example-ajax').select2({
ajax: {
url: '/product/api/search',
dataType: 'json',
success: function (data) {
$.each(response, function () {
$('#mytable').append('<tr><td>' + this.product_name + '</td><td>' + this.product_price + '</td></tr>');
});
}
}
});
There are different methods of what you can render, you can reload whole table or just rows that you need.
Related
Laravel 8 with User & teamwork together
I am working on data-table javascript, and controller but the error is still there, and it bugged me as I am not knowledgeable with laravel as I only work on laravel for one month (it's perfect code and way better than WordPress PHP). I look at details on google, but most of them are details write dropdowns based on the hardcode selection list.
I'm using
<label for="selectTeam">{{ __('Team')}}</label>
<select class="form-control" id="selectTeam">
#foreach($teamlistfliter as $row)
<option>{{ $row->team }}</option>
#endforeach
</select>
and it is working fine and but not related to data table show user in the list
but when I want this dropdown can query to list of users, that where it became error
here are the controller pages I wrote
class TeamUserListController extends Controller
{
public function index(Request $request)
{
if ($request->ajax())
{
$teamlistfliter = User::join('teams', 'teams.id', '=', 'users.current_team_id')
->get(['users.name as username', 'teams.name as team', 'users.firstname as first_name', 'users.surname as surname']);
return Datatables::of($teamlistfliter)
->filter(function ($instance) use ($request) {
if ($request->get('team') == '0' || $request->get('team') == '1') {
$instance->where('team', $request->get('team'));
}
if (!empty($request->get('search'))) {
$instance->where(function($w) use($request){
$search = $request->get('search');
$w->orWhere('name', 'LIKE', "%$search%")
->orWhere('email', 'LIKE', "%$search%");
});
}
})
->rawColumns(['team'])
->make(true);
}
return view('teamlistfliter');
}
}
and blade pages
<div class="row">
<div class="col-sm-12">
<div class="card">
<div class="card-header d-block">
<div class="col-md-6">
<div class="form-group">
<label for="selectTeam">{{ __('Team')}}</label>
<select class="form-control" id="selectTeam">
#foreach($teamlistfliter as $row)
<option>{{ $row->team }}</option>
#endforeach
</select>
</div>
</div>
</div>
<div class="card-body">
<div class="dt-responsive">
<table id="simpletable"
class="table table-striped table-bordered nowrap">
<thead>
<tr>
<th>{{ __('First Name')}}</th>
<th>{{ __('Surname')}}</th>
<th>{{ __('Username')}}</th>
<th>{{ __('Team')}}</th>
</tr>
</thead>
<tbody>
#foreach($teamlistfliter as $row)
<tr>
<td>{{ $row->first_name }}</td>
<td>{{ $row->surname }}</td>
<td>{{ $row->username }}</td>
<td>{{ $row->team }}</td>
</tr>
#endforeach
</tbody>
<tfoot>
<tr>
<th>{{ __('First Name')}}</th>
<th>{{ __('Surname')}}</th>
<th>{{ __('Username')}}</th>
<th>{{ __('Team')}}</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- push external js -->
#push('script')
<script src="{{ asset('plugins/DataTables/datatables.min.js') }}"></script>
<script src="{{ asset('js/datatables.js') }}"></script>
<script type="text/javascript">
$(function () {
var table = $('#selectTeam').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{ route('teamlistfliter.index') }}",
data: function (d) {
d.approved = $('#selectTeam').val(),
d.search = $('input[type="search"]').val()
}
},
columns: [
{data: 'firstname', name: 'firstname'},
{data: 'surname', name: 'surname'},
{data: 'username', name: 'username'},
{data: 'email', name: 'email'},
{data: 'team', name: 'team'},
]
});
$('#selectTeam').change(function(){
table.draw();
});
});
</script>
#endpush
#endsection
I fear I miss something as I assume the issue is $teamlistfilter outside the statement.
[2021-09-03 19:28:18] local.ERROR: Undefined variable: teamlistfliter (View: C:\Ergnation-rowing\resources\views\teamlistfliter.blade.php) {"view":{"view":"C:\\Ergnation-rowing\
esources\\views/teamlistfliter.blade.php","data":{"errors":"<pre class=sf-dump id=sf-dump-1080913330 data-indent-pad=\" \"><span class=sf-dump-note>Illuminate\\Support\\ViewErrorBag</span> {<a class=sf-dump-ref>#1449</a><samp data-depth=1 class=sf-dump-expanded>
#<span class=sf-dump-protected title=\"Protected property\">bags</span>: []
</samp>}
</pre><script>Sfdump(\"sf-dump-1080913330\", {\"maxDepth\":3,\"maxStringLength\":160})</script>
"}},"userId":1,"exception":"[object] (Facade\\Ignition\\Exceptions\\ViewException(code: 0): Undefined variable: teamlistfliter (View: C:\\Ergnation-rowing\
esources\\views\\teamlistfliter.blade.php) at C:\\Ergnation-rowing\
esources\\views/teamlistfliter.blade.php:45)
Try get basic value from controller and use JavaScript to write on blade pages
public function index()
{
$teamlistfliter = User::join('teams', 'teams.id', '=', 'users.current_team_id')
->get(['users.name as username', 'teams.name as team', 'users.firstname as first_name', 'users.surname as surname']);
return view('teamlistfliter', compact('teamlistfliter'));
}
and use JavaScript on blade pages
<div class="row">
<div class="col-sm-12">
<div class="card">
<div class="card-header d-block">
<h3>{{ __('Team')}}</h3>
<div class="Team-filter">
<select id="TeamFilter" class="form-control">
<option value="">Show All</option>
#foreach($teamlistfliter as $row)
<option>{{ $row->team }}</option>
#endforeach
</select>
</div>
</div>
<div class="card-body">
<div class="dt-responsive">
<table id="filterTable"
class="table table-striped table-bordered nowrap">
<thead>
<tr>
<th>{{ __('First Name')}}</th>
<th>{{ __('Surname')}}</th>
<th>{{ __('Username')}}</th>
<th>{{ __('Team')}}</th>
</tr>
</thead>
<tbody>
#foreach($teamlistfliter as $row)
<tr>
<td>{{ $row->first_name }}</td>
<td>{{ $row->surname }}</td>
<td>{{ $row->username }}</td>
<td>{{ $row->team }}</td>
</tr>
#endforeach
</tbody>
<tfoot>
<tr>
<th>{{ __('First Name')}}</th>
<th>{{ __('Surname')}}</th>
<th>{{ __('Username')}}</th>
<th>{{ __('Team')}}</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- push external js -->
#push('script')
<script src="{{ asset('plugins/DataTables/datatables.min.js') }}"></script>
<script src="{{ asset('js/datatables.js') }}"></script>
<script>
$("document").ready(function () {
$("#filterTable").dataTable({
"searching": true
});
//Get a reference to the new datatable
var table = $('#filterTable').DataTable();
//Take the Team filter drop down and append it to the datatables_filter div.
//You can use this same idea to move the filter anywhere withing the datatable that you want.
$("#filterTable_filter.dataTables_filter").append($("#TeamFilter"));
//Get the column index for the Team column to be used in the method below ($.fn.dataTable.ext.search.push)
//This tells datatables what column to filter on when a user selects a value from the dropdown.
//It's important that the text used here (Team) is the same for used in the header of the column to filter
var TeamIndex = 0;
$("#filterTable th").each(function (i) {
if ($($(this)).html() == "Team") {
TeamIndex = i; return false;
}
});
//Use the built in datatables API to filter the existing rows by the Team column
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex) {
var selectedItem = $('#TeamFilter').val()
var Team = data[TeamIndex];
if (selectedItem === "" || Team.includes(selectedItem)) {
return true;
}
return false;
}
);
//Set the change event for the Team Filter dropdown to redraw the datatable each time
//a user selects a new filter.
$("#TeamFilter").change(function (e) {
table.draw();
});
table.draw();
});
</script>
#endpush
#endsection
that should should be working
This is what I'm looking for and thank you so much!
I am trying to add the Jquery UI Sortable behaviour to an existing table (which is populated through a JavaScript Code).I think I followed the right steps from this link Using Jquery UI sortable to sort table rows, yet the order never changes, it's as if the controller function is never called. Here is my code
This is the code in my twig
<table class="table">
<thead>
<tr>
<th class="col-md-2" data-sort="none">{{ 'element.single'|trans }}<span class="required"> *</span></th>
<th class="col-md-2"data-sort="none">{{ 'operation.type.single'|trans }}<span class="required"> *</span></th>
<th class="col-md-4" data-sort="none">{{ 'inspection.point.label'|trans }}<span class="required"> *</span></th>
<!--09:26-----edit-->
<th class="col-md-2" data-sort="none">{{ 'inspection.point.referenceValue'|trans }}</th>
<th class="col-md-2" data-sort="none">
{#bouton import des gammes d'opérations #}
{% if 'inspection_sheet_edit' != app.request.attributes.get('_route') %}
{% if is_granted('INSPECTIONSHEET_IMPORT',equipment) %}
<div class="btn-group pull-right">
<button class="btn btn-default btn-sm" type="submit" name="import">
<i class="fa fa-file"></i>
<span>{{ 'import'|trans }}</span>
</button>
</div>
{% endif %}
{% endif %}
</th>
</tr>
</thead>
<tbody id="tabledivbody" ></tbody>
</table>
<script>
var fixHelper = function(e, ui) {
ui.children().each(function() {
$(this).width($(this).width());
});
return ui;
}
$("#tabledivbody").sortable({
items: "tr",
cursor: 'move',
opacity: 0.6,
helper: fixHelper,
update: function() {
sendOrderToServer();
}
});
function sendOrderToServer() {
var order = $("#tabledivbody").sortable("serialize");
var test='console text';
$.ajax({
type: "POST", dataType: "json", url: "{{ path('post_order') }}",
data: order,
success: function(response) {
if (response.status == "success") {
console.log(test);
window.location.href = window.location.href;
} else {
alert('Some error occurred');
}
}
});
}
</script>
This is the function in my controller
/**
* #Route("/post_order", name="post_order")
*/
public function updateInspectionPointOrder(Request $request)
{
$em=$this->getDoctrine()->getManager();
$data = json_decode($request->request->get('request'));
$count=1;
foreach ($data->getPoints() as $point) {
//$count++;
$em->getRepository('EpxInspectionBundle:InspectionPoint')->updateDisplayOrderInspectionPoint($count,$point->getId());
$em->flush();
$point->setDisplayOrder($count);
$em->getRepository('EpxInspectionBundle:InspectionPoint')->updateDisplayOrderInspectionPoint($count,$point->getId());
$em->flush();
$count++;
}
}
Any insights please.
Iam learning symfony and I want to build a shop system for my school project. I want to send the list of items that the user select to another controller i don't know how.
here is my ShowItemAction
public function ShowItemAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$form = $this->createFormBuilder()
->add('search', 'textbox', array(
'attr' => array(
'label' => false
)))->getForm();
$form->handleRequest($request);
if (($form->isSubmitted()) && ($form->isValid())) {
$formdata = $request->request->get('form');
$search = $formdata['search'];
$products_Repo = $em->getRepository('MyShopBundle:Products')->GetProducts($search);
return $this->render('MyShopBundle:Products:show.html.twig',array(
'form' => $form->createView(),
'products'=> $products_Repo
));
}
return $this->render('MyShopBundle:Products:show.html.twig',array(
'form' => $form->createView()
));
}
and my show.html.Twig
{% block body%}
<div id="cart-content">
</div>
<div class="cart-buttons">
<button id="cart">View Shopping Cart</button>
<button id="clear-cart">Clear Cart</button>
</div>
{{ form(form) }}
{% if products is defined %}
<table>
<thead>
<tr>
<th>Partner-Name</th>
<th>ProductNr</th>
<th>Description</th>
<th>price</th>
</tr>
</thead>
<tbody>
{% for product in products %}
<tr>
<td><div class="partner">{{product.partner}}</div></td>
<td><div class="partnerdata" data-value="{{ product.id }}">{{ product.productnr }}</div></td>
<td><div class="description"> {{ product.description }}</div></td>
<td><div class="price">{{ product.price }}</div></td>
<td class="counter"><input type="number" name="count" min="1" step="1"></td>
<td class="cart">
<button type='submit'>in den Warenkorb</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
{% endblock %}
my javascript:
$('.cart').click(function (event) {
event.preventDefault();
var closestTr = $(this).closest('tr');
var ref = closestTr.find('.partner').text();
var data_value = closestTr.find('.partnerdata').data('value');
var productNr= closestTr.find('.partnerdata').html();
var price= closestTr.find('.price').html();
var count = closestTr.find('input').val();
if (count < 1) {
}
else {
$(".cart-content").prepend(HS_ref + "|" + data_value + "|" + herstellerNr + "|" + count + "|" + vk);
}
});
I can see the data which the user has selected(inside <div id="cart-content"></div>) but I don't know how to send those contents perhaps as a POST to the controller.
Something like this: https://www.codeofaninja.com/2013/04/shopping-cart-in-php.html
I am working on Symfony 2.7
You can do this with AJAX
First, you need to get the html data
Second, you have to send this data to the controller
Third, you have to get the data in the controller
Here is an example :
First "you need to get the html data"
HTML :
<div id="cart-content" data-route="{{ path('get_user_card_items') }}">
<span data-item-id="item1" data-quantity="2"></span>
<span data-item-id="item2" data-quantity="1"></span>
<span data-item-id="item3" data-quantity="5"></span>
</div>
JS
/**
* Get the content of #cart-content
*/
function getCartItems() {
var items = [];
$('#cart-content span').each(function(){ // loop into all span
var item = { // create an item object who get all the data
'id' : $(this).attr('data-item-id'),
'quantity' : $(this).attr('data-quantity'),
}
items.push(item); // push into an array
});
return items;
}
Second "you have to send this data to the controller"
JS
function sendCartItems() {
$.ajax({
url: $('#cart-content').attr('data-route'), // here is a route variable
method: 'POST',
data: {items: getCartItems()},
success: function (data) {
// do some stuff when it's send
}
});
}
Third "you have to get the data in the controller"
CustomController.php
class CustomController extends Controller
{
/**
* #Route("/getUserCardItems", name="get_user_card_items")
*/
public function getUserCardItemsAction(Request $request)
{
$items = $request->get('items');
var_dump($items);die; // display for you the items to see if it's works (look into the networks console tab on google chrome)
// some stuff like sending items to database...
}
}
Access network tab google chrome
And you done ;)
I am trying to create simple "admin" page for my blog. For now I want to create some "dynamic" behaviour which will lock/unlock user. Then I want to replace single table row with another, taken from json. I wrote a simple function but unfortunatelly it is not working properly...
When I use constant value for user id (just for tests) it works, but only for ONE row. Other buttons do nothig. Then I tried to send id to my function as a parameter but now it says it doesn't exist in my TWIG (what is true).
I want to make it work, because reloading all page when you only locked one user or did another single action, is not a good idea.
How can I make my function work in a good way?
SCRIPT
$(document).ready(function(){
$(".LockUserButton").click(function(id){
$(this).closest("tr").toggleClass('locked progress-bar-striped');
$.ajax({
type: 'POST',
url: "{{ path('lock_ajax', {'id': id }) }}",
data: { user_id: "{{ user.id }}" },
dataType: 'json',
success: function () {
$(this).closest("tr").toggleClass('locked progress-bar-striped');
}
});
});
});
TWIG
<div class="table-content">
{% for u in users %}
{% if u.locked %}
<tr id="tableRow" class="locked progress-bar-striped">
{% else %}
<tr id="tableRow" class="">
{% endif %}
{% if u.roles[0] == 'ROLE_SUPER_ADMIN' %}
<td id="roles">
<h4><span class="glyphicon glyphicon-star admin-star" data-toggle="tooltip" data-placement="right" title="{{ u.roles[0] }}"></span></h4>
</td>
<td>{{ u.username }}</td>
<td>{{ u.email }}</td>
<td>
<span class="glyphicon glyphicon-lock admin-lock" data-toggle="tooltip" data-placement="right" title="Cannot modyfi this user!"></span>
</td>
<td>
<span class="glyphicon glyphicon-lock admin-lock" data-toggle="tooltip" data-placement="right" title="Cannot modyfi this user!"></span>
</td>
{% else %}
<td id="roles">
<h4><span class="glyphicon glyphicon-star-empty user-star" data-toggle="tooltip" data-placement="right" title="{{ u.roles[0] }}"></span></h4>
</td>
<td>{{ u.username }}</td>
<td>{{ u.email }}</td>
<td>
<div class="btn btn-custom LockUserButton">LOCK USER WITHOUT RELOADING</div>
</td>
<td>
<a href="/profile/admin/delete_user/{{ u.id }}" onclick="return confirm('{{ 'user.deleting'|trans }}')">
<div class="btn btn-custom hvr-grow">
<span class="glyphicon glyphicon-trash"></span>
</div>
</a>
</td>
{% endif %}
</tr>
{% endfor %}
</div>
CONTROLLER ACTION
/**
* #Route("/profile/ajax/{id}", name="lock_ajax")
*/
public function ajaxLock($id, Request $request)
{
$entityManager = $this->getDoctrine()->getManager();
$user = $entityManager->getRepository('AppBundle:User')->find($id);
if($user->isLocked()){
$user->setLocked(false);
}else{
$user->setLocked(true);
}
$entityManager->persist($user);
$entityManager->flush();
$result = array();
$result[0] = $user;
return new JsonResponse($result);
}
Thanks to Artamiel I have finally figure it out! Here's the solition for my case:
1) I have added data-id="{{ u.id }}" attribute to my button. Now i have access to my entity ID.
2) I have modify a little my script:
$(document).ready(function(){
$(".LockUserButton").click(function(){
//get user id from twig layout
var user = $(this).data("id");
//ajax request
$.ajax({
type: 'POST',
url: "/profile/ajax/"+user,
data: { user_id: "user" },
dataType: 'json',
context: this,
success: function () {
//i've wrote some function to toggle html
$(this).toggleText('{{ 'user.unlocked'|trans }}', '{{ 'user.locked'|trans }}');
//find table row and toggle classes when button clicked and request ok
$(this).closest("tr").toggleClass('locked progress-bar-striped');
},
error: function(){
alert("Error!");
}
});
});
});
I have a basic but functional search mechanism in my Symfony2 project.This will query and display back to the user the data using Doctrine2 LIKE expression.But I want to make more 'dynamic' and more 'user-friendly' by adding Ajax functionality.I added some Ajax code in my controller, but I don't know how to make it work.The image loader is just 'spinning' without displaying the results.
//controller
public function searcAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$query = $this->getRequest()->get('query');
if(!$query) {
if(!$request->isXmlHttpRequest()) {
return $this->redirect($this->generateUrl('voters_list'));
} else {
return new Response('No results.');
}
}
$city = $em->getRepository('DuterteBundle:City')->findCity($query);
if($request->isXmlHttpRequest()) {
if('*' == $query || !$city || $query == '') {
return new Response('No results.');
}
//display a another page
return $this->render('DuterteBundle:City:list1.html.twig', array('city' => $city));
}
return $this->render('DuterteBundle:City:search.html.twig', array('city' => $city));
}
// routing
search:
path: /search
defaults: { _controller:DuterteBundle:City:Searc }
requirements:
//search.html.twig
{% extends '::base.html.twig' %}
{% block body %}
<div id="city">
{% include 'DuterteBundle:City:list1.html.twig' with {'city': city} %}
</div>
{% endblock %}
//list1.html.twig
{% block body %}
<div class="page-header">
<h4>City/Municipality/Town and Its Corresponding Numbers of Voters</h4>
</div>
<table class="table table-hover table-bordered table-condensed">
<thead>
<tr>
<th>City</th>
<th>Votes</th>
<th>Percent</th>
</tr>
</thead>
<tbody>
{% for city in city %}
<tr>
<td>{{ city }}</td>
<td>{{ number_votes_city(city.id) }}</td>
<td></td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
My search form is embedded in navbar in the main layout.
<div class="col-sm-3 col-md-3" id="search">
<form class="navbar-form" role="search" action ="{{ path('search')}}" method ="post">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search city/town" name="query" value="{{ app.request.get('query') }}" id="search_keywords">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="fa fa-search"></i></button>
<img id="loader" src="{{ asset('bundles/duterte/images/loader.gif') }}" style="vertical-align: middle; display: none" />
</div>
</div>
</form>
//repository
public function findCity($city)
{
return $this
->createQueryBuilder('c')
->select('c')
->where('c.name LIKE :name_city')
->setParameter('name_city', '%'.$city.'%')
->orderBy('c.name', 'ASC')
->getQuery()
->getResult()
;
}
and finally the js file
$(document).ready(function()
{
$('.search input[type="submit"]').hide();
$('#search_keywords').keyup(function(key)
{
if(this.value.length >= 3 || this.value == '') {
$('#loader').show();
$('#city').load(
$(this).parent('form').attr('action'),
{ query: this.value ? this.value + '*' : this.value },
function() {
$('#loader').hide();
}
);
}
});
});
Any help is appreciated
The same functionality, but a different approach. Listen to the keyup event on the search box
and then make ajax calls to a controller that returns the list of matched results as json. Check the response and
based on the status of the response, hide the existing listing and replace its contents with the markup returned in the
json response for the AJAX call.
Here, the example is for search in user listing.
Table markup on the twig file
<div id="user-list-div">
<table class="records_list" id="user-list">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Username</th>
<th>Password</th>
<th>Salt</th>
<th>Email</th>
<th>Isactive</th>
<th>Createdat</th>
<th>Updatedat</th>
<th>Isbillableuser</th>
<th>Isdeleted</th>
<th>Actions</th>
</tr>
</thead>
<tbody id = "user-table">
{% for entity in entities %}
<tr>
<td>{{ entity.id }}</td>
<td>{{ entity.name }}</td>
<td>{{ entity.username }}</td>
<td>{{ entity.password }}</td>
<td>{{ entity.salt }}</td>
<td>{{ entity.email }}</td>
<td>{{ entity.isActive }}</td>
<td>{% if entity.createdAt %}{{ entity.createdAt|date('Y-m-d H:i:s') }}{% endif %}</td>
<td>{% if entity.updatedAt %}{{ entity.updatedAt|date('Y-m-d H:i:s') }}{% endif %}</td>
<td>{{ entity.isBillableUser }}</td>
<td>{{ entity.isDeleted }}</td>
<td>
<ul>
<li>
show
</li>
<li>
edit
</li>
</ul>
</td>
</tr>
{% endfor %}
</tbody>
Search form markup
<div class="col-lg-6">
<div class="input-group">
<input type="text" class="form-control" id="search-field">
<span class="input-group-btn">
<button class="btn btn-default" type="button">Go!</button>
</span>
</div>
</div>
javascript part
<script>
$(function(){
console.log('desperate for');
var searchField = $('#search-field');
var userTable = $('#user-table');
var userListDiv = $('#user-list-div');
searchField.keyup(function(evt){
console.log($(this).val());
$.ajax({
url: '{{ path('admin_user_search') }}',
method: "POST",
data: "id=" + $(this).val() ,
dataType: 'html',
success: function(result, request) {
var parsedData =JSON.parse(result);
console.log(parsedData);
if(parsedData.status ==='success'){
console.log('hete');
userListDiv.empty();
userListDiv.html(parsedData.data);
}else{
//handle no result case
}
}
});
});
});
</script>
ajax_template.html.twig file
The same table markup as given above
controller action
public function searchuserAction(){
$em = $this->getDoctrine()->getManager();
$request = $this->get('request');
$searchParameter = $request->request->get('id');
//call repository function
$entities = $em->getRepository('LBCoreBundle:User')->findUsersForname($searchParameter);
$status = 'error';
$html = '';
if($entities){
$data = $this->render('LBCoreBundle:User:ajax_template.html.twig', array(
'entities' => $entities,
));
$status = 'success';
$html = $data->getContent();
}
$jsonArray = array(
'status' => $status,
'data' => $html,
);
$response = new Response(json_encode($jsonArray));
$response->headers->set('Content-Type', 'application/json; charset=utf-8');
return $response;
}
Respository function
public function findUsersForname($name){
$em = $this->getEntityManager();
$query = $em->createQuery("SELECT e FROM LBCoreBundle:User e
WHERE e.username LIKE '%$name%'");
$entities = $query->getResult();
return $entities;
}