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
Related
Privet all!
I'm new to Symfony 4 and generally to PHP and OOP in general. I was helped to make the form using FormCollection the code looks so
AbilityContoller.php
/**
* #Route("/edit", name="ability_edit_all")
*/
public function edit(Request $request)
{
$abilitys = $this->getDoctrine()->getRepository(Ability::class)->findAll();
$form = $this->createForm(AbilityArrayType::class, ['abilitys' => $abilitys]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
foreach ($form->getData()['abilitys'] as $ability){
$this->getDoctrine()->getManager()->persist($ability);
}
$this->getDoctrine()->getManager()->flush();
$this->addFlash('notice', 'Your changes were saved!');
return $this->redirectToRoute('ability_edit_all');
}
return $this->render('ability/edit.all.html.twig', [
'form' => $form->createView()
]);
}
and screenshot
you see that my record with the form has both tags with a choiceType and a simple input
And I also figured out myself with knp_paginator, because if I output more than 15 records with FormCollection, I get an error about the lack of memory in php. I made a static table where I output all my records, sorting and filtering works, pagination is broken as it should.
here is the code
ServiceFile.php
class AbilityService{
protected $em;
protected $container;
public function __construct(EntityManagerInterface $entityManager, ContainerInterface $container)
{
$this->em = $entityManager;
$this->container = $container;
}
public function ReturnData($request){
$em = $this->em;
$container = $this->container;
$query = $em->createQuery(
'
SELECT
t.idItem,
t.code,
t.reloadTime,
t.durationTime,
t.idAbilityType
FROM
App\Entity\Ability t
'
);
dump($query);
//$result = $query->execute();
$pagenator = $container->get('knp_paginator');
$results = $pagenator->paginate(
$query,
$request->query->getInt('page', 1),
$request->query->getInt('limit', 10)
);
return ($results);
}
}
and controller
use App\Service\ServiceFile;
/**
* #Route("/test-edit", name="ability_test_edit_all")
*/
public function edit_test(AbilityService $query, Request $request)
{
$data = $query->ReturnData($request);
return $this->render('ability/edit.alltest.html.twig',[
'form' => $data,
]);
}
here screenshot
Work a perfect!!
I bet I can not figure out how to make the same result, but with FormCollection?
The second question, if it turns out to be pagination, will filtering and sorting work from knp_paginator?
ok,
ok, something happened and it's not right for mine, but Pagination and sorting + filtering work only on <input> tags, inside <select> <option selected> var </ select> nothing works, but the solution is working
controllerFile.php
/**
* #Route("/edit", name="ability_edit_all")
*/
public function edit(AbilityService $abilityService, Request $request)
{
$data = $abilityService->ReturnData($request);
$form = $this->createForm(AbilityArrayType::class, ['abilitys' => $data->getItems()]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
foreach ($form->getData()['abilitys'] as $properties){
dump($properties);
$ability = $this->getDoctrine()->getRepository(Ability::class)->find($properties['id']);
$ability->setIdItem($properties['idItem']);
$ability->setCode($properties['code']);
$ability->setReloadTime($properties['reloadTime']);
$ability->setDurationTime($properties['durationTime']);
$ability->setIdAbilityType($properties['idAbilityType']);
dump($ability);
$this->getDoctrine()->getManager()->persist($ability);
}
$this->getDoctrine()->getManager()->flush();
$this->addFlash('notice', 'Your changes were saved!');//проделать со всеми см edit.html.twig
return $this->redirectToRoute('ability_edit_all');
}
return $this->render('ability/edit.all.html.twig', [
'form' => $form->createView(),
'paginator' => $data
]);
}
twig tempalte
{% extends 'base.html.twig' %}
{% block title %}Ability edit all{% endblock %}
{% block body %}
<style>
label{display:none}
</style>
<h1>Ability edit all</h1>
<a class="btn-add mar-bot-top-20" href="{{ path('ability_new') }}"><i class="fas fa-plus"></i> Create new</a>
<div class="row">
<div class="col-4 text-center">
<div class="navigation">
{{ knp_pagination_render(paginator) }}
</div>
</div>
<div class="col-8 text-left">
<div class="filtration">
{{ knp_pagination_filter(paginator, {
't.idItem': 'IdItem',
't.code': 'Code',
't.reloadTime': 'ReloadTime',
't.durationTime': 'DurationTime',
't.idAbilityType': 'IdAbilityType',
}) }}
</div>
</div>
</div>
<table class="table">
<tr>
<th>{{ knp_pagination_sortable(paginator, 'idItem', 't.idItem') }}</th>
<th>{{ knp_pagination_sortable(paginator, 'Code', 't.code') }}</th>
<th>{{ knp_pagination_sortable(paginator, 'ReloadTime', 't.reloadTime') }}</th>
<th>{{ knp_pagination_sortable(paginator, 'DurationTime', 't.durationTime') }}</th>
<th>{{ knp_pagination_sortable(paginator, 'idAbilityType', 't.idAbilityType') }}</th>
</tr>
{{ form_start(form) }}
{% for ability in form.abilitys %}
<tr>
<td>{{ form_row(ability.idItem) }}</td>
<td>{{ form_row(ability.code) }}</td>
<td>{{ form_row(ability.reloadTime) }}</td>
<td>{{ form_row(ability.durationTime) }}</td>
<td>{{ form_row(ability.idAbilityType) }}</td>
</tr>
{% else %}
<tr>
<td colspan="9">no records found</td>
</tr>
{% endfor %}
{{ form_end(form) }}
</table>
<div class="row">
<div class="col-4 text-center">
<div class="navigation">
{{ knp_pagination_render(paginator) }}
</div>
</div>
<div class="col-8 text-left">
<div class="filtration">
{{ knp_pagination_filter(paginator, {
't.idItem': 'IdItem',
't.code': 'Code',
't.reloadTime': 'ReloadTime',
't.durationTime': 'DurationTime',
't.idAbilityType': 'IdAbilityType',
}) }}
</div>
</div>
</div>
<a class="btn-add" href="{{ path('ability_new') }}"><i class="fas fa-plus"></i> Create new</a>
{% for message in app.flashes('notice') %}
<div class="flash-notice">
{{ message }}
</div>
{% endfor %}
{% endblock %}
and ServiceFile.php
<?php
namespace App\Service;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\Ability;
class AbilityService{
protected $em;
protected $container;
public function __construct(EntityManagerInterface $entityManager, ContainerInterface $container)
{
$this->em = $entityManager;
$this->container = $container;
}
public function ReturnData($request){
$em = $this->em;
$container = $this->container;
$query = $em->createQuery(
'
SELECT
t.id,
t.idItem,
t.code,
t.reloadTime,
t.durationTime,
t.idAbilityType,
t.dateCreated,
t.author,
t.dateChange,
t.lastAuthor
FROM
App\Entity\Ability t
'
);
$pagenator = $container->get('knp_paginator');
$results = $pagenator->paginate(
$query,
$request->query->getInt('page', 1),
$request->query->getInt('limit', 6)
);
return ($results);
}
}
if anyone can tell how to implement sorting within <select> <option selected> var </ select>, you can use <th> {{knp_pagination_sortable (paginator, 'idItem', 't.idItem')}} </ th>
write please!
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]);
}
i am fetching values from the database and displaying it into a table using php laravel. Latitude logitude value am fetching and displaying in my table. there is another column address, so in that column i need to display the address by converting corresponding lat long value from the database. Can anyone tell how i can write the code for that?
my view blade is giving below
#extends('app')
#section('content')
</br></br></br></br></br></br></br></br>
<div class="templatemo-content-wrapper">
<div class="templatemo-content">
<ol class="breadcrumb">
<li><font color="green">Home</font></li>
<li class="active">Vehicle Report</li>
</ol>
<h1>Vehicle Report</h1>
<p></p>
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table id="example" class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th>Date</th>
<th>Time</th>
<th>Status</th>
<th>Lat/Long</th>
<th>Speed</th>
<th>Altitude</th>
<th>Odometer</th>
<th>Fuel</th>
<th>Address</th>
</tr>
</thead>
<tbody>
#foreach($devices as $device)
<tr>
<td>{{ date('Y/m/d H:i:s',($device->timestamp)) }}</td>
<td>{{ date('H:i:s',($device->timestamp)) }}</td>
<td>{{--}}{{ $device->statusCode }}--}}
#if($device->statusCode == '61715')
Stop
#elseif($device->statusCode=='62465')
Ignition_On
#elseif($device->statusCode=='61713')
Start
#elseif($device->statusCode=='61714')
InMotion
#elseif($device->statusCode=='62467')
Ignition_Off
#else
Speeding
#endif
</td>
<td>{{ round($device->latitude,5).'/'.round($device->longitude,5) }}</td>
<td>{{ $device->speed }}</td>
<td>{{ round($device->altitude) }}</td>
<td>{{ round($device->odometer) }}</td>
<td>{{ ($device->fuelLevel*100).'%' }}</td>
<td>{{ ?????????? }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</br>
</br></br></br></br>
Controller page is
class ReportController extends Controller
{
public $type = 'Device';
public function getAdd()
{
$vehicles = DB::table('device')->get();
return view('reports.vehicleDetail')->with('vehicles', $vehicles);
}
public function get(Request $request)
{
$account = Account::select('accountID')->where('accountID','=','gts')->get();
foreach ($account as $acc) {
$abc = $acc->accountID;
}
try {
$device_id = $request['deviceID'];
$from = strtotime($request['Fdate']);
$to = strtotime($request['Tdate']);
$devices=DB::table('device as b')
->join('eventdata as a', 'a.deviceID', '=', 'b.deviceID')
->where('a.deviceID', '=', $device_id)
->where('a.accountID', '=', $abc)
->where('a.creationTime', '>=', $from)
->where('a.creationTime', '<=', $to)
->select('a.accountID', 'a.deviceID', 'b.description', 'a.timestamp','a.statusCode',
'a.latitude', 'a.longitude', 'a.speedKPH as speed', 'a.heading', 'a.altitude', 'a.address', 'a.distanceKM as distance', 'a.odometerKM as odometer', 'a.IbatVolts', 'a.EbatVolts', 'a.ITempr', 'a.fuelLevel', 'a.inputState', 'a.IgnRuntime', 'GPSFixType', 'a.GPSPDOP', 'a.isTollRoad')->get();
// $devices = DB::table('eventdata')->get();
return view('reports.vehicleReport')->with('devices', $devices);
} catch (ModelNotFoundException $err) {
//Show error page
}
}
}
Thanks in advance.
You need to use Reverese Geocoding. Google maps API would be the best choice.
<?php
if(isset($_POST['latitude'])){
$lat=$_POST['latitude'];
$long=$_POST['longitude'];
$address=file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$long&key=YOUR_API_KEY");
$json_data=json_decode($address);
$full_address=$json_data->results[0]->formatted_address;
}
?>
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;
}
i have a view that contains a form. the form's url is the address of view that the form is in it.
in controller i pass a variable to the view when the user hit the button in the form.
but my view has an error says the variable i passed to it is undefined.
here is my code
my view:
#extends('layouts.master')
#section('content')
<?php
$category = Category::lists('name','name');
$priority = Priority::lists('name','name');
$lesson = Lesson::lists('name','name');
$count = 1;
?>
{{ Form::open(array('action' => 'createQuizController#find', 'method' => 'POST', 'id' => 'search_question')) }}
<div>
{{ Form::label('quiz_cat', 'نام دسته بندی') }}
{{ Form::select('quiz_cat', array('/'=>'انتخاب کنید')+$category, null, ['id' => 'cat_select']) }}
</div>
<div>
{{ Form::label('quiz_less','نام درس') }}
{{ Form::select('quiz_less',$lesson, null, ['id' => 'les_select']) }}
</div>
<div>
{{ Form::label('quiz_prio','سطح سوال') }}
{{ Form::select('quiz_prio',array('/'=>'انتخاب کنید')+$priority, null, ['id' => 'prio_select']) }}
</div>
<div>
{{Form::label('date_start','تاریخ شروع')}}
{{Form::input('date','date_start',null,array('id' => 'date_start'))}}
</div>
<div class='form-group'>
{{ Form::submit('جستجو', ['class' => 'btn btn-primary']) }}
</div>
{{ Form::close() }}
<iframe width="690px" height="300px" scrolling="yes">
{{ Form::open(array('method' => 'POST', 'id' => 'add_question')) }}
<div class="col-lg-10 col-lg-offset-1">
<div class="table-responsive" id="question_table">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ردیف</th>
<th>عنوان سوال</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach ($res as $quiz)
<tr>
<td align="center" width="100px">
<?php echo $count++; ?>
</td>
<td align="center" width="200px">{{ $quiz->title }}</td>
<td align="center" width="200px"><input type="checkbox" name="select_question[]" id="{{ $quiz->lesson_id }}" value="{{ $quiz->id }}"></td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
{{ Form::submit('افزودن', ['class' => 'btn btn-primary']) }}
{{ Form::close() }}
</iframe>
#stop
my controller:
<?php
class createQuizController extends BaseController {
public function find()
{
$prio = Input::get('quiz_prio');
$res1 = DB::select("select id from priority pr where '$prio' = pr.name");
$r1 = $res1[0]->id;
$cat = Input::get('quiz_cat');
$res2 = DB::select("select id from categories cat where '$cat' = cat.name");
$r2 = $res2[0]->id;
$les = Input::get('quiz_less');
$res3 = DB::select("select id from lesson less where '$les' = less.name");
$r3 = $res3[0]->id;
$sdate = Input::get('date_start');
$res = DB::select("select * from quiz where categories_id='$r2' and lesson_id='$r3' and priority_id='$r1' and date_start='$sdate'");
return View::make('cquiz')->with('res',$res);
}
public function addQuestion()
{
$a = array();
$a[] = Input::get('select_question');
var_dump($a[]);
/*foreach($a as $b) {
$c = DB::select("select name from lesson where '$b'=id" );
var_dump($c);
}*/
}
}
my route:
Route::post('/cquiz/','createQuizController#find');
Route::post('/addQuestion/','createQuizController#addQuestion');
try this:
return View::make('cquiz')->withRes($res);
and in the view you can access '$res' (or {{ $res }} etc)