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!
Related
I'd like to add autocomplete="off" to all <form> tag in my symfony project and I'm looking for the best way to do such.
I don't want to change all templates to change {{form_start}} call or manually add attribute on form object in controller, neither add listener or subscriber on each form.
I am looking for a global solution, like a service that change all forms in one call.
I think if it's the default behavior of all your forms, it's better to think about a root solution.
Extending type by default will do the trick
class FormTypeExtension extends AbstractTypeExtension
{
/**
* Return the class of the type being extended.
*/
public static function getExtendedTypes(): iterable
{
// return FormType::class to modify (nearly) every field in the system
return [FormType::class];
}
public function buildView(FormView $view, FormInterface $form, array $options): void
{
if (isset($view->vars['method'])) { // Make sure we're on the base form
$view->vars['attr']['autocomplete'] = isset($view->vars['attr']['autocomplete']) ? $view->vars['attr']['autocomplete'] : "off"; // let the possibility to override for specific forms
}
}
}
you just have to use it like that
class DefaultController extends AbstractController
{
/**
* #Route("/", name="home")
*/
public function home() {
$form1 = $this->createForm(DemoType::class, new Demo());
$form2 = $this->createForm(DemoType::class, new Demo(), ['attr' => ['autocomplete' => "on"]]);
return $this->render('demo.html.twig', ['form1' => $form1->createView(), 'form2' => $form2->createView()]);
}
}
I get what you want to achive. autocomplete is an HTML attribute so it is not directly managed by symfony, as much as I know.
The fastest solution that I found is just to add the following code (below) to the base.html.twig file.
<script>
$('form').attr('autocomplete','off');
</script>
It's going to be applied to all Forms in this page, BUT normally all the pages extend the base.html.twig, so it'll be implemented in all pages. Ah keep in mind that it's a JQuery, so of course you need to include it.
here is an example of a possible implementation:
FILE: base.html.twig
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}Welcome!{% endblock %}</title>
{% block stylesheets %}{% endblock %}
</head>
<body>
{% block body %}{% endblock %}
{% block javascripts %}{% endblock %}
// add this -------------------------------
<script>
$('form').attr('autocomplete','off');
</script>
// ----------------------------------------
</body>
</html>
Check this link maybe you'll find something more useful https://www.scotsscripts.com/blog/html-css-trick-how-to-turn-off-auto-complete.html
I hope that I helped you. :-) have a nice day, Bye
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:
I'm following the example of the official website.
$enqueue->front([
'as' => 'vueJS',
'src' => Helper::assetUrl('/js/vue.js')
]);
And I need it to load in a view, I use the example of the official page.
<!DOCTYPE html>
<html>
<head>
<title>Profesores</title>
</head>
<body>
<h1>{{ title }}</h1>
<p>{{ content }}</p>
</body>
</html>
I use a controller to load the view
public function getProfesores()
{
$profesores = Profesor::all();
return view('#MyPlugin/profesores/lista.twig', [
'title' => 'My Demo',
'content' => 'Congrats on your demo view.',
'data'=> json_response($profesores->toArray())
]);
}
Maybe it's easy but it does not work for me, can someone help me?
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.
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')
}
})
}}