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
Related
I have several JavaScript files created via Webpack. Besides the general app.js I also have JavaScript files that are only used on certain pages. After the build process, I have included the new JavaScript file included. The JS file is also loaded successfully. But the JavaScript does not run.
What do I have to do to make it work? Or am I already doing something wrong?
Goal run my build/myjs.js file and print console.log('Hello world!');
webpack.config.js
Encore
// …
.addEntry('app', './assets/app.js')
.addEntry('myjs', './assets/scripts/my.js')
// …
build/myjs.js
(self["webpackChunk"] = self["webpackChunk"] || []).push([["myjs"],{
/***/ "./assets/scripts/myjs.js":
/*!********************************!*\
!*** ./assets/scripts/myjs.js ***!
\********************************/
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__)
=> {
__webpack_require__(/*! core-js/modules/es.array.for-each.js */
"./node_modules/core-js/modules/es.array.for-each.js");
__webpack_require__(/*! core-js/modules/es.object.to-string.js */
"./node_modules/core-js/modules/es.object.to-string.js");
__webpack_require__(/*! core-js/modules/web.dom-collections.for-each.js */
"./node_modules/core-js/modules/web.dom-collections.for-each.js");
__webpack_require__(/*! core-js/modules/es.array.concat.js */
"./node_modules/core-js/modules/es.array.concat.js");
__webpack_require__(/*! core-js/modules/es.promise.js */
"./node_modules/core-js/modules/es.promise.js");
console.log('Hello world!');
// ...
My show.html.twig file where I need the special JavaScript:
{% extends 'test/base.html.twig' %}
{% block javascripts %}
{{ parent() }}
<script src="{{ asset('build/myjs.js') }}"></script>
{% endblock %}
You have add in your twig file the encore_entry_script_tags() helpers function. As parameter you pass the name of the file which you want to include. In your case myjs.
The same you have to do with CSS files. But then use the encore_entry_link_tags() helper function. With the name from the file as parameter. Dont forget to use addStyleEntry('targetName',source).
You just need to use encore_entry_script_tags function, as shown here.
In your case, it would be something like:
{% extends 'test/base.html.twig' %}
{{ encore_entry_script_tags('myjs') }}
The file will be loaded automatically, and as any JS file will be executed when loaded.
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!
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
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.
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.