I have an huge issue with my shopping cart system. The problem is when I select products and try to send through ajax to server side, products not always counted. I have to use ajax to collect all data because I'm using JQuery datatables plugin.
List of products should looks like this:
Incorrect view is a screen from my windows firefox, correct view is from my chromium broswer on linux. It looks like there is some dependency on which browser running my webservice. I'm testing my webservice on server production and it works properly only on my chromium browser.
My buddy said there is in inappropriate data sent in Ajax code.
Here's my HTML template:
{% block content %}
<div class="panel-body">
<form method="post" action="{{ path('order') }}" id="orderList">
<table class="table table-bordered table-striped mb-none" id="datatable-default">
<thead>
<tr>
<th>Nazwa</th>
<th>Kod</th>
<th>Cena netto(zł)</th>
<th class="hidden-xs">Cena brutto(zł)</th>
<th class="hidden-xs">Ilość</th>
</tr>
</thead>
<tbody>
{% for product in products %}
<tr>
<td>{{ product.productName }}</td>
<td>{{ product.code }}
</td>
<td>{{ product.priceNetto }}</td>
<td class="center hidden-xs">{{ product.priceBrutto }}</td>
<td>
<input type="number" class="spinner-input form-control" min="0" value="0" name="cart[{{ product.code }}]" />
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% if app.user != null %}
<button id="getData" type="submit" class="btn btn-primary hidden-xs">Zamów</button>
{% else %}
<p>Zaloguj się aby dokonać zamówienia</p>
{% endif %}
</form>
</div>
{% endblock %}
AJAX code:
$(document).ready(function () {
$('#getData').click( function (event) {
//event.preventDefault();
var paginator = $('#datatable-default').DataTable();
var dat = paginator.$('input').serialize();
console.log(dat);
console.log(decodeURIComponent(dat));
$.ajax({
type: "POST",
url: $('#orderList').attr('action'),
data: {'orders': decodeURIComponent(dat)},
success: function (response) {
console.log(response)
}
});
});
});
And my server side code:
public function orderAction(Request $request)
{
$session = $request->getSession();
$totalPriceNetto = 0;
$totalPriceBrutto = 0;
$user = $this->getUser();
$address = $user->getStreet();
if($request->isXmlHttpRequest())
{
$repository = $this->getDoctrine()->getRepository('AppBundle:Products');
$jsitems = $request->get('orders');
$items = [];
parse_str($jsitems, $items);
$orderItems = [];
foreach ($items['cart'] as $index=>$item)
{
if( $item != 0)
{
$orderItems[$index] = $item;
$orders[$index] = $repository->findBy(['code' => $index]);
//$orders[$index][0]->setPriceBrutto(str_replace(',', '.', str_replace('.', '', $orders[$index][0]->getPriceBrutto())));
//$orders[$index][0]->setPriceNetto(str_replace(',', '.', str_replace('.', '', $orders[$index][0]->getPriceNetto())));
$orders[$index]['value'] = $item;
}
}
$session->set('orders', $orders);
$session->set('orderItems', $orderItems);
foreach ($orders as $index=>$item)
{
$productObject = $item[0];
$totalPriceNetto += floatval(str_replace(',', '.', str_replace('.', '', $productObject->getPriceNetto()))) * (float)$item['value'];
$totalPriceBrutto += floatval(str_replace(',', '.', str_replace('.', '', $productObject->getPriceBrutto()))) * (float)$item['value'];
}
$totalPriceBrutto = round($totalPriceBrutto - ($totalPriceBrutto * $user->getPromo()/100), 2);
$session->set('dd', $totalPriceNetto);
$session->set('de', $totalPriceBrutto);
return $this->render("/default/shop/makeOrder.html.twig", ['totalPriceNetto' => $totalPriceNetto, 'totalPriceBrutto' => $totalPriceBrutto, 'address' => $address]);
}
if($session->has('dd') && $session->has('de'))
{
$totalPriceBrutto = $session->get('de');
$totalPriceNetto = $session->get('dd');
$session->remove('dd');
$session->remove('de');
}
return $this->render("/default/shop/makeOrder.html.twig", ['totalPriceNetto' => $totalPriceNetto, 'totalPriceBrutto' => $totalPriceBrutto, 'address' => $address]);
}
Related
i i want to select the info by the file link , for example in database in first line :
file link : src/java/son3.wav | word : mailing
secund line in DB : file link : src/java/son3.wav | word: smtp
3rd line in DB : file link : src/java/son2.wav | word : server
I want to show like this in the html.twig ::
id : 1 | file link : src/java/son3.wav | word : mailing , smtp
id : 2 | file link : src/java/son2.wav | word : server
so that select all the words in DB that have the same file link, I hope this explains what I'm after.
I'm using symfony 3.4 and this is how it showed in my interface :
https://i.stack.imgur.com/7EQ63.jpg
this is pic of my table in DB :
https://i.stack.imgur.com/MEYaJ.jpg
this is the code of file twig :
<table class="table table-striped">
<thead>
<tr>
<th>Id</th>
<th>File Link</th>
<th>Words</th>
</tr>
</thead>
<tbody>
{% for result in resultats %}
<tr>
<td>{{ result.id }}</td>
<td>{{ result.indexeFichier.fichierUrl }}</td>
<td>{{ result.indexeMot.motValeur }}</td>
</tr>
{% endfor %}
</tbody>
</table>
and this is the code of file controller :
public function IndexAction()
{
////////////////////////////////////////////
$em = $this->getDoctrine()->getManager();
$resultats = $em->getRepository('AppBundle:Indexe')->findAll();
return $this->render('userfiles/result.html.twig', array(
'resultats' => $resultats,
));
}
I think it's impossible to do it only with DQL query, post processing can help:
public function IndexAction()
{
////////////////////////////////////////////
$em = $this->getDoctrine()->getManager();
$tmp = $em->getRepository('AppBundle:Indexe')->findAll();
$tmp2 = [];
foreach ($tmp as $v) {
if (!isset($resultats[$v->getIndexeFichier()->getFichierUrl()])) {
$resultats[$v->getIndexeFichier()->getFichierUrl()] = [];
}
$resultats[$v->getIndexeFichier()->getFichierUrl()][] = $v->indexeMot()->getMotValeur();
}
$resultats = [];
$i = 1;
foreach ($tmp2 as $k=>$v) {
$resultats[] = ['id' => $i++, 'fichierUrl' => $k, 'motValeur' => join(', ', $v)];
}
return $this->render('userfiles/result.html.twig', array(
'resultats' => $resultats,
));
}
and in template
....
{% for result in resultats %}
<tr>
<td>{{ result.id }}</td>
<td>{{ result.fichierUrl }}</td>
<td>{{ result.motValeur }}</td>
</tr>
{% endfor %}
....
also if your db is mysql, you can try to use GROUP_CONCAT() function
I'm new to Symfony, and I'm trying to filter my table with a search field. I'm using KnpPaginatorBundle to paginate and sort my table, and I've created a form to filter my request ( method GET )
It is generally working, but when I use spaces or underscores in my search input, it doesn't work, I assume there is something to do about the GET method and the way to encode the text, but I don't know how.
Here's my code :
View :
<div class="row">
<div class="well row">
<form action="" method="get">
<div class="col-md-2">
<label for="famille">Famille d'articles</label>
<select name="famille">
<option value="0">Toutes</option>
{% for famille in listFamilles %}
<option value="{{ famille.id }}" {% if data.famille is defined %} {% if famille.id == data.famille %} selected {% endif %} {% endif %}>{{ famille.nom }}</option>
{% endfor %}
</select>
</div>
<div class="col-md-4">
<input type="checkbox" name="rds" {% if data.rds == 1 %} checked {% endif %}>
<label for="rds" style="margin-left:5px">Montrer les articles en rupture de stock</label>
</div>
<div class="col-md-4">
<label for="recherche">Recherche</label>
<input name="recherche" style="width:100%" type="text" placeholder="Recherche" {% if data.recherche is defined %} value="{{ data.recherche }}" {% endif %}>
</div>
<div class="col-md-2" style="text-align:center">
<button type="submit" class="btn btn-primary">Rechercher</button>
</div>
</form>
</div>
<div class="well row">
<table class="table table-bordered table-striped" style="width: 100%" cellspacing="0">
<thead>
<tr>
<th>{{ knp_pagination_sortable(listArticles, 'Référence client', 'a.ref_article') }}</th>
<th>{{ knp_pagination_sortable(listArticles, 'Référence interne', 'a.ref_logistique') }}</th>
<th>{{ knp_pagination_sortable(listArticles, 'Famille', 'f.nom') }}</th>
<th>{{ knp_pagination_sortable(listArticles, 'Libellé', 'a.libelle') }}</th>
<th>{{ knp_pagination_sortable(listArticles, 'Alerte', 'a.stock_alerte') }}</th>
<th>{{ knp_pagination_sortable(listArticles, 'Stock', 'a.stock_actuel') }}</th>
</tr>
</thead>
<tbody id="bodyListeArticles">
{% for article in listArticles %}
<tr>
<td>{{ article.refArticle }}</td>
<td>{{ article.refLogistique }}</td>
<td>{{ article.famille.nom }}</td>
<td>{{ article.libelle }}</td>
<td>{{ article.StockAlerte }}</td>
<td>{{ article.StockActuel }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="navigation text-center">
{{ knp_pagination_render(listArticles) }}
</div>
</div>
</div>
Controller :
public function listeAction(Request $request) {
if ($this->get('security.authorization_checker')->isGranted('ROLE_OPERATEUR')) {
$session = $request->getSession();
if ($session->get('client_id')) {
$clientId = $session->get('client_id');
} else {
$request->getSession()->getFlashBag()->add('info', 'Vous devez sélectionner un client pour accéder à la liste de ses articles.');
return $this->redirectToRoute('gr_bo_liste_clients');
}
} elseif ($this->get('security.authorization_checker')->isGranted('ROLE_SUPERCOLLABORATEUR') || ($this->get('security.authorization_checker')->isGranted('ROLE_COLLABORATEUR') && $this->getUser()->getListeArticles())) {
$clientId = $this->getUser()->getClient()->getId();
} else {
$request->getSession()->getFlashBag()->add('info', 'Vous n\'avez pas les permissions requises pour accéder à cette page.');
return $this->redirectToRoute('gr_bo_liste_commandes');
}
$em = $this->getDoctrine()->getManager();
$data = [];
$data['clientId'] = $clientId;
if ($request->query->getAlnum('recherche')) {
$data['recherche'] = $request->query->getAlnum('recherche');
}
if ($request->query->getAlnum('famille') && $request->query->getAlnum('famille') != "0") {
$data['famille'] = $request->query->getAlnum('famille');
}
if ($request->query->getAlNum('rds') == "on" || ($request->query->getAlnum('rds') == "" && $request->query->getAlnum('famille') == "" && $request->query->getAlnum('recherche') == "")) {
$data['rds'] = 1;
} else {
$data['rds'] = 0;
}
$listArticles = $em->getRepository('GRBackOfficeBundle:Article')->getQueryArticles($data);
/**
* #var $paginator \Knp\Component\Pager\Paginator
*/
$paginator = $this->get('knp_paginator');
$result = $paginator->paginate(
$listArticles, $request->query->getInt('page', 1), $request->query->getInt('limit', 5)
);
$listFamilles = $em->getRepository('GRBackOfficeBundle:Famille')->findAll();
return $this->render('GRBackOfficeBundle:Article:liste_articles.html.twig', array(
'listArticles' => $result,
'listFamilles' => $listFamilles,
'data' => $data
));
}
Repository :
public function getQueryArticles($data) {
$query = $this->createQueryBuilder('a')
->leftJoin('a.images', 'i')
->addSelect('i')
->leftJoin('a.type_stockage', 't')
->addSelect('t')
->leftJoin('a.famille', 'f')
->addSelect('f');
if (array_key_exists('famille', $data)) {
$query->andWhere('f.id = :famille')
->setParameter('famille', $data['famille']);
}
if (array_key_exists('rds', $data)) {
if ($data['rds'] == 0) {
$query->andWhere('a.stock_actuel > 0');
}
}
if (array_key_exists('recherche', $data)) {
$query->andWhere('a.ref_article LIKE :recherche OR a.ref_logistique LIKE :recherche OR a.libelle LIKE :recherche')
->setParameter('recherche', '%' . $data['recherche'] . '%');
}
$query->leftJoin('a.sousfamille', 's')
->addSelect('s')
->leftJoin('a.client', 'c')
->addSelect('c')
->andWhere('c.id = :client')
->setParameter('client', $data['clientId'])
->orderBy('a.ref_article', 'ASC')
->getQuery();
return $query;
}
When I use a space or an underscore in my "recherche" search filter, my table appears empty, and it seems to delete the spaces or the underscore so if I try with "John Doe" or "John_Doe", it will return me the results for "JohnDoe", which is empty.
If someone have an idea of how I can proceed, it will be appreciated !
You can use urlencode on your data.recherche. But there also more natural way to do this in twig
I have a Symfony app which allows CRUD operations on some events and also searching for them. The problem I get is when trying to get the results I'm searching for displayed without refreshing the page. It's the first time I'm using ajax and I think it's something wrong with the function. When I search for a word in any event name, the page is not refreshing and it shows undefined instead of showing the entries.
I appreciate any help!
Here's the method from the Controller:
public function ajaxListAction(Request $request){
//fetch the data from the database and pass it to the view
$em = $this->getDoctrine()->getManager();
$searchTerm = $request->get('search');
$form = $this->createFormBuilder()
->add('search', SubmitType::class, array('label' => 'Search', 'attr' => array('class' => 'btn btn-primary', 'style' => 'margin-bottom:15px')))->getForm();
$organizer = array();
if($searchTerm == ''){
$organizer = $this->getDoctrine()->getRepository('AppBundle:Organizer')->findAll();
}
elseif ($request->getMethod() == 'GET') {
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
$organizer = $em->getRepository('AppBundle:Organizer')->findAllOrderedByName($searchTerm);
}
$response = new JsonResponse();
$results = array();
foreach ($organizer as $value) {
$results[] = json_encode($value);
}
return $response->setData(array(
'results' => $results
));
}
and here's the script for the search:
$(document).ready( function(event) {
$("#search").submit(function(event) {
event.preventDefault(); //prvent default submission event
$form = $(this);
var data = $('#search_term').val();
$.ajax({
url: '/ajax',
type: "GET",
data: {'search' : data },
success: function(response){
var output = '';
for (var i = 0; i < response.length; i++) {
output[i] = output + response;
}
$('#ajax_results').html('<tr><td>' + response.id + '</td></tr>' + '<tr><td>' + response.name + '</td></tr>' + '<tr><td>' + response.dueDate + '</td></tr>');
}
})
});
});
and the index.html.twig file for displaying the data:
{% extends 'base.html.twig' %}
{% block body %}
<h2 class="page-header"> Latest events </h2>
<form id="search" method="GET" action="">
<input type="text" name="search" id="search_term" />
<input type="submit" name="submit" value="Search" />
</form>
<hr />
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Event</th>
<th>Due Date</th>
<th></th>
</tr>
</thead>
<tbody id="ajax_results">
{% for Events in organizer %}
<tr>
<th scope="row">{{Events.id}}</th>
<td>{{Events.name}}</td>
<td>{{Events.dueDate|date('j F, Y, g:i a')}}</td>
<td>
View
Edit
Delete
</td>
</tr>
{% endfor %}
<table class="table table-striped">
{% if organizer|length > 0 %}
{% for items in organizer %}
{% endfor %}
{% else %}
<tr>
<td colspan="2">No matching results found!</td>
</tr>
{% endif %}
</table>
</tbody>
</table>
{% endblock %}
Lets try to refactor your code first. Perhaps it will bring you near the solution.
public function ajaxListAction(Request $request){
$searchTerm = $request->get('search');
//don't need form here
if($searchTerm == ''){
$organizer = $this->getDoctrine()->getRepository('AppBundle:Organizer')->findAll();
}else{
//repository should search by searchterm in next step
$organizer = $this->getDoctrine()->getRepository('AppBundle:Organizer')->findAllOrderedByName($searchTerm);
}
return new JsonResponse($organizer);
}
and javascript:
$(document).ready( function(event) {
$("#search").submit(function(event) {
event.preventDefault(); //prvent default submission event
$form = $(this);
var data = $('#search_term').val();
$.ajax({
url: '/ajax',
type: "GET",
data: {'search' : data },
success: function(response){
$('#ajax_results').html('');
$.each(response, function(key, value) {
console.log(key, value);
$('#ajax_results').append('<tr><td>' + response[key].id + '</td></tr>' + '<tr><td>' + response[key].name + '</td></tr>' + '<tr><td>' + response[key].dueDate + '</td></tr>');
});
}
})
});
});
Please tell what do you see in js console after submit the search?
I managed to make it work. The problem was that I didn't have all the fields sent into the array in the jsonSerialize() method in the Entity file and thus the fields were showing undefined.
I also completed the append method in the .js file in order to have the whole markup replicated upon the ajax call.
Thanks to Rawburner for the suggestions!
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 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;
}