Getting JSON error while trying to use the AliDatatableBundle - symfony

I'm trying to use the AliDatatableBundle and I follow every step as docs say, so this is how my controller looks like:
public function indexAction(Request $request) {
$this->_datatable();
return $this->render('PICommonBundle:Default:index.html.twig');
}
private function _datatable() {
return $this->get('datatable')
->setEntity("PIProyectoBundle:Proyectos", "p")
->setFields(
array(
"Nombre" => 'p.nombre',
"Centros" => 'c.descripcion',
"Unidades" => 'u.descripcion',
"_identifier_" => 'p.id')
)
->addJoin('p.centros', 'c', \Doctrine\ORM\Query\Expr\Join::INNER_JOIN)
->addJoin('p.unidades', 'u', \Doctrine\ORM\Query\Expr\Join::INNER_JOIN);
}
public function gridAction() {
return $this->_datatable()->execute();
}
And this is my template:
{% extends '::base.html.twig' %}
{% block content %}
<link href="{{ asset('bundles/alidatatable/css/demo_table.css') }}" type="text/css" rel="stylesheet" />
<link href="{{ asset('bundles/alidatatable/css/smoothness/jquery-ui-1.8.4.custom.css') }}" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="{{ asset('bundles/alidatatable/js/jquery.datatable.inc.js') }}"></script>
<script type="text/javascript" src="{{ asset('bundles/alidatatable/js/jquery.dataTables.min.js') }}"></script>
{{
datatable({
'edit_route' : 'editar-asistencia',
'delete_route' : 'eliminar-asistencia',
'js' : {
'sAjaxSource' : path('informes')
}
})
}}
{% endblock %}
But any time I try to execute the page I get this error:
DataTables warning (table id = 'ali-dta_98f13708210194c475687be6106a3b84'):
DataTables warning: JSON data from server could not be parsed. This is caused > by a JSON formatting error.
Any advice? I'm using latest jQuery 1.10.2.

are you spanish?
(i´m too !!)
I think your problem is whit sAjaxSource.
Read this tip:
Ali en github
At the end of post comment:
"I took a look on your code and even tested it: your error is too simple , the "sAjaxSource" have to include the route for the grid action and not the index action "
In my case this solved:
In (bundle) routing.yml:
empleados_grid:
pattern: /empleados_grid
defaults: { _controller: MyBundle:Empleados:grid }
and in twig template:
{{ datatable({
'edit_route' : 'empleados_update',
'delete_route' : 'empleados_delete',
'js' : {
'sAjaxSource' : path('empleados_grid')
}
})
}}

Related

How to use Select2 Ajax in Symfony combined with Twig

I'm trying to use Select2 Ajax in my HTML page to seach through my dataset. I have multiple errors:
Search bar is almost invisible
If does not shown any data
ProductController
/**
* #Route("/api/product/v1/select2search", name="api_product_search")
*/
public function viewAction()
{
$products = $this->productRepository->findAll();
foreach ($products as $entity) {
$response1[] = array(
'id' => $entity['id'],
);
$response2[] = array(
'name' => $entity['name'],
);
}
return new JsonResponse(([$response1,$response2]));
}
My twig file:
{% extends 'base.html.twig' %}
{% block body %}
<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">
<select class="js-data-example-ajax"></select>
<script>
$('.js-data-example-ajax').select2({
ajax: {
url: 'http://127.0.0.1:8000/api/product/v1/select2search',
dataType: 'json'
// Additional AJAX parameters go here; see the end of this chapter for the full code of this example
}
});
</script>
{% endblock %}
The current visual screen:
You can not see the bar as described above.
My goal to achieve is this:

Flash message is not shown when trying to use getFlashBag()

Hello friendly people,
I am following a tutorial on Symfony, in which I try to display a flash message, but even though I followed the instructions, no flash message is shown.
Here is my function viewAction in my AdvertController:
public function viewAction($id)
{
return $this->render('NeoPlatformBundle:Advert:view.html.twig', array('id' => $id));
}
public function addAction(Request $request)
{
$session = $request->getSession();
$session->getFlashBag()->add('info' , 'This is a flash message');
$session->getFlashBag()->add('info', 'This is a second flash message');
return $this->redirectToRoute('neo_platform_view', array('id' => 5));
}
When I go to
http://localhost/Symfony/web/app_dev.php/platform/add
I only get this:
My view.html.twig is as follows:
{# src/Neo/PlatformBundle/Resources/view/Advert/view.html.twig #}
<!DOCTYPE html>
<html>
<head>
<title>Display of the announcement {{id}}</title>
</head>
<body>
<h1>Display of the announcement n°{{id}}!</h1>
<div>
{#We display all flash messages, whose name is "info" #}
{% for message in app.session.flashbag.get('info') %}
<p>Flash message : {{message}}</p>
{% endfor %}
</div>
</body>
</html>
Any clue?
Thanks in advance!

Which file should I override to change edit form template in Sonata Admin?

I follow this tutorial to add a preview of my image file in my sonata admin (symfony3)
http://symfony.com/doc/current/bundles/SonataAdminBundle/cookbook/recipe_image_previews.html
But I not being able to add the CSS parte. The image is too large.
Should I override one of the sonata templates for it? If yes, which file I change and how do I do it? [I'm pretty new in sonata/symfony3]
If not, how should I add the css file in the project?
My actual code is exactly as the tutorial:
class ImageAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
// get the current Image instance
$image = $this->getSubject();
// use $fileFieldOptions so we can add other options to the field
$fileFieldOptions = array('required' => false);
if ($image && ($webPath = $image->getWebPath())) {
// get the container so the full path to the image can be set
$container = $this->getConfigurationPool()->getContainer();
$fullPath = $container->get('request')->getBasePath().'/'.$webPath;
// add a 'help' option containing the preview's img tag
$fileFieldOptions['help'] = '<img src="'.$fullPath.'" class="admin-preview" />';
}
$formMapper
// ... other fields ...
->add('file', 'file', $fileFieldOptions)
;
}
// ...
}
You'll need to add some code to include a CSS file in your Symfony project. Something similar to
{% stylesheets 'bundles/app/css/*' filter='cssrewrite' %}
<link rel="stylesheet" href="{{ asset_url }}" />
{% endstylesheets %}
Then you'd put the following CSS from the tutorial into that file.
img.admin-preview {
max-height: 200px;
max-width: 200px;
}
You can learn more about including CSS files with Symfony here.
First you need to make a template that extends SonataAdminBundle:CRUD:base_edit.html.twig, here is an example:
{# BlastBaseEntitiesBundle:CRUD:edit.html.twig #}
{% extends 'SonataAdminBundle:CRUD:base_edit.html.twig' %}
{# ... #}
Then create your css file in Resources/Public/css.
Execute the command bin/console assets:install to publish your stylesheet to the web/bundles directory.
{# blastcore/css corresponds to BlastCoreBundle/Resources/Public/css and web/bundles/blastcore/js #}
<link rel="stylesheet" href="{{ asset(blastcore/css/style.css) }}" />
http://symfony.com/doc/current/assetic/asset_management.html
Now you need to tell sonata to use your template for your admin.
you can do that in the service definition :
admin.yml
blast_base_entities.admin.search_index_entity:
class: Blast\BaseEntitiesBundle\Admin\SearchIndexEntityAdmin
arguments: [~, Blast\BaseEntitiesBundle\Entity\SearchIndexEntity, BlastCoreBundle:CRUD]
tags:
- name: sonata.admin
manager_type: orm
group: admin
label: SearchIndexEntity
calls:
- [ setTemplate, [edit, BlastBaseEntitiesBundle:CRUD:edit.html.twig]]
https://sonata-project.org/bundles/admin/master/doc/reference/templates.html#crudcontroller-actions-templates

symfony2 redirect every request from listener doesn't works

i try to redirect every request to a specific form. If my user don't accept the form, he can't go anywhere. I saw a lot of tuto but when i try to redirect he just loading my page many times or throw me "The page is not redirected properly".
config.yml :
project.listener.before_request:
class: Project\ClientBundle\Listener\BeforeControllerListener
arguments: ["#router", "#security.context"]
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
BeforeControllerListener.php
namespace Project\ClientBundle\Listener;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Project\ClientBundle\Model\InitializableControllerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernel;
class BeforeControllerListener
{
protected $security_context;
private $router;
public function __construct($router, SecurityContextInterface $security_context)
{
$this->router = $router;
$this->security_context = $security_context;
}
public function onKernelRequest( getResponseEvent $event ){
$user = $this->security_context->getToken()->getUser();
$route = 'confidential';
if ( HttpKernel::MASTER_REQUEST != $event->getRequestType() || !is_object($user) || $route == $event->getRequest()->get('_route') ) {
// don't do anything if it's not the master request
return;
}else{
$redirectUrl = $this->router->generate( $route );
$event->setResponse(new RedirectResponse($redirectUrl));
}
}
}
Any idea ? Thanks
Ok, the page is loaded correctly, but no css. Maybe something is wrong in the layout ?
The bug appear only after redirect.
<head>
<meta charset="UTF-8" />
{% block head_style %}
<link href='http://fonts.googleapis.com/css?family=Ubuntu' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Oxygen+Mono' rel='stylesheet' type='text/css'>
{% stylesheets
'bundles/bduclient/css/mopabootstrapbundle.css'
'bundles/bduclient/css/redactor.css'
'bundles/bduclient/css/font-awesome.min.css'
'bundles/bduclient/css/select2-bootstrap.css'
'bundles/bduclient/css/jquery-ui-1.9.2.custom.min.css'
'bundles/bduclient/css/select2.css'
'bundles/bduclient/css/simple-sidebar.css'
'bundles/bduclient/css/bootstrap-datetimepicker.min.css'
'bundles/bduclient/css/datepicker3.css'
'bundles/bduclient/css/style.css'
%}
{#
filter='less, cssrewrite, yui_css' #}
<link href="{{ asset_url }}" type="text/css" rel="stylesheet" media="screen" />
{% endstylesheets %}
{% endblock head_style %}
<title>{% block title %}Base de Donnée Universelle{% endblock title %}</title>
<link rel="shortcut icon" href="{{ asset('favicon.ico') }}" />
{% block head_bottom %}
{% endblock head_bottom %}
To me this is good. It works for all the page except this one..
I have this error several times in firebug console :
SyntaxError: syntax error <!DOCTYPE html>
But only on this page after redirect..
Thanks, i tried this, because i redirect when my user is logged and if i'm not on confidential page. But still loading the page many times but now he load the page confidential without css/js.
if( HttpKernel::MASTER_REQUEST != $event->getRequestType() ){
// skip redirect if its not the main request
return;
}else if( is_object( $user ) && $route != $event->getRequest()->get('_route')){
// redirect if its the main request and an anonymous user asks for 'confidential' route
$redirectUrl = $this->router->generate( $route );
$event->setResponse(new RedirectResponse($redirectUrl));
}
try changing
( HttpKernel::MASTER_REQUEST != $event->getRequestType() || ... || ... || ...)
into
if( HttpKernel::MASTER_REQUEST != $event->getRequestType() )
// skip redirect if its not the main request
else if(!is_object($user) && $route == $event->getRequest()->get('_route'))
// redirect if its the main request and an anonymous user asks for 'confidential' route
Maybe you can try to add these lines at the beginning of your onKernelRequest method:
if( $event->getRequest()->getRequestFormat() == 'css' || $event->getRequest()->getRequestFormat() == 'js' ) )
{
return;
}
It will not take into account your js and css files.

symfony2 and facebox ajax twig content not displaying

enter link description here
I am trying about this:
text
I have this in my twig
<a href='{{ path('likes_show_names') }}' rel='facebox'>
And than in controller:
$view= $this->renderView('WallBundle:Statuses:likes_names.html.twig');
return new Response($view);
No error appear the network (chrome) is displaying code get 200. Facebox open the pop up but the connntent.. is missing...
When i check response => preview its displaying: This request has no preview available
What i am doing wrong please?
I put Facebox in my web/ directory. The file structure looks like this:
web/facebox
web/js/jquery.js
Then, on the routing, I set my default and the ajax-called controller:
vendor_some_bundle_homepage:
pattern: /
defaults: { _controller: VendorSomeBundle:Default:index }
vendor_some_bundle_test:
pattern: /test
defaults: { _controller: VendorSomeBundle:Default:ajax }
Next, I created a simple controller for both routes:
<?php
namespace Vendor\SomeBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
public function indexAction()
{
return $this->render('VendorSomeBundle:Default:indexTest.html.twig');
}
public function ajaxAction()
{
return $this->render('VendorSomeBundle:Default:ajaxTest.html.twig');
}
}
Then, and I think the most important file for you, the page where there is a link that open facebox :
<!-- indexTest.html.twig -->
<html>
<head>
<link href="{{ asset('facebox/src/facebox.css') }}" media="screen" rel="stylesheet" type="text/css"/>
</head>
<body>
<a href="{{ path('vendor_some_bundle_test') }}" rel='facebox'>click me</a>
<script src="{{ asset('js/jquery.js') }}" type="text/javascript"></script>
<script src="{{ asset('facebox/src/facebox.js') }}" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('a[rel*=facebox]').facebox();
});
</script>
</body>
</html>
Important: you should take care of your assets and of the routing. If there is some errors, they should be written in your app/log/dev.log file, or at last in your apache error.log.
Finally, create the view that will be included:
{# ajaxTest.html.twig #}
This is <em>some</em> remote content
This sample gave me the following result:
Note: there is still some assetic errors (see the close button at the right of the image), because I installed facebox quickly. The point of your question was the access to remote content, and here you have a sample you can follow to find your mistake.

Resources