symfony 2.8 login error doesn't display - symfony

I have little problem. My symfony app after bad login doesn't show error mesage in login file ;/ . After typing good login & pasword everthing is ok, im logged & redirected to dashboard.
Sorry for my English:)
here is my controller
class LoginController extends Controller
{
/**
* #Route("/login", name="login")
*
* #Template()
*/
public function loginAction(Request $Request)
{
$Session = $this->get('session');
// Login Form
if($Request->attributes->has(SecurityContextInterface::AUTHENTICATION_ERROR)){
$loginError = $Request->attributes->get(SecurityContextInterface::AUTHENTICATION_ERROR);
}else{
$loginError = $Session->remove(SecurityContextInterface::AUTHENTICATION_ERROR);
}
if(isset($loginError)){
$this->get('session')->getFlashBag()->add('error', $loginError->getMessage());
}
$loginForm = $this->createForm(new LoginType());
return array(
'loginForm' => $loginForm->createView()
);
}
here is block form_errors code in view file form_template.html.twig:
{% block form_errors %}
{% spaceless %}
{% if errors|length > 0 %}
{% for error in errors %}
<div class="alert alert-danger">
<button class="close" data-close="alert"></button>
<span> {{ error.message|trans }} </span>
</div>
{% endfor %}
{% endif %}
{% endspaceless %}
{% endblock %}
Thanks :)

Try this :)
{% block form_errors %}
{% spaceless %}
{% if errors|length > 0 %}
{% for error in app.session.flashbag.get('error') %}
<div class="alert alert-danger">
<button class="close" data-close="alert"></button>
<span> {{ error|trans }} </span>
</div>
{% endfor %}
{% endif %}
{% endspaceless %}
{% endblock %}

Related

add link in #UniqueEntity message

hi i am using symfony 5.4, and trying to add html code to uniqueentity message:
/**
* #ORM\Entity(repositoryClass=UserRepository::class)
* #ORM\Table(indexes={#ORM\Index(name="user",columns={"id","credential","nickname","email","status"})})
* #UniqueEntity(
* fields={"email"},
* message="este Correo ya esta en Uso; Dirigete a la Activacion de Cuentas! <a href='/account_activation'>Activate</a>"
* )
*/
class User implements UserInterface, PasswordAuthenticatedUserInterface
in this case I want a link to be shown in the error but I don't get it:
this is the twig template:
{% extends 'base.html.twig' %}
{% block body %}
{# display any flash message #}
{% for label, messages in app.flashes %}
{% for message in messages %}
<div class="alert alert-{{ label }} alert-dismissible fade show">
{{ message }}
</div>
{% endfor %}
{% endfor %}
{{ form(registration_form) }}
{% endblock %}
any idea how i can achieve it?
update
i try to add raw error filter:
{% extends 'base.html.twig' %}
{% block body %}
{{ error.message|raw }}
{% for label, messages in app.flashes %}
{% for message in messages %}
<div class="alert alert-{{ label }} alert-dismissible fade show">
{{ message }}
</div>
{% endfor %}
{% endfor %}
{{ form(registration_form) }}
{% endblock %}
but get this error:
How do you display it on the front? If you use Twig, maybe you forgot to use raw filter?
{{ error.message|raw }}
After two weeks of research:
Use the message property that uses uniqueentity in annotation, it is not the correct way (is a bad practice) if you want to implement any element/structure html.
all properties are encoded to avoid xss attacks, there are 2 ways to follow using the controller:
forget about the html tag and use a direct redirect to the desired path instead of a link:
if (count($form['email']->getErrors(true)) > 0) {
return $this->redirectToRoute('account_activation');
}
implement a custom error handler and display the error concatenated to the html tag:
if (count($form['email']->getErrors(true)) > 0) {
$this->addFlash(
'warning',
'your account need to be activated! Click Here!'
);
}
Note: implementing the second option requires adding the Flash Messages output to the form template.
There is another unverified method that the github site gave me but I could not verify its functionality:
https://github.com/symfony/symfony/issues/44755#issuecomment-999156755
{% extends 'base.html.twig' %}
{% form_theme registration_form _self %}
{% block form_errors %}
{%- for error in errors -%}
{{ error.message | raw }}
{%- endfor -%}
{% endblock %}
{% block body %}
{{ form_errors(registration_form) }}
{{ form(registration_form) }}
{% endblock %}

Symfony form builder - how to put form title in h2 selector?

I want my form title to be displayed in h2 selector. I did something like that but it throws me an error "exception: "An exception has been thrown during the rendering of a template ("Notice: Undefined offset: -1").""
// how should I change THIS part? To change only the main form title/label?
// I made it work somehow but then it changes all labels... Is there some
// selector which allows to style MAIN title of the form?
{% block form_label %}
{% spaceless %}
<h2>{{ form_label(form) }}</h2>
{% endspaceless %}
{% endblock form_label %}
I've heard that I shouldn't put it in my project file in h2 selector just in form template. It's cleaner and even though documentation doesn't forbide that I was encouraged to do it another way and that's how I want to try it.
{% form_theme form 'Forms/base_form.html.twig' %}
{{ form_start(form) }}
{{ form_label(form, 'Project title', { 'label_attr': {'class': 'main-form-label'} }) }}
// so as I shouldn't put all that line in <h2> can I somehow do it in template between {% block form_label %} ?
{{ form_row(form.title, {'label': 'My title'}) }}
{{ form_row(form.isComplete, {'label': 'Dropdown'}) }}
{{ form_row(form.comment, {'label': 'Comment'}) }}
{{ form_row(form.submit, {'label': 'Submit'}) }}
{{ form_end(form) }}
Also... Whats the difference/what should I use - {% block form_label %} or {%- block form_label -%}
My whole template:
{% block form_label %}
{% spaceless %}
<h2>{{ form_label(form) }}</h2>
{% endspaceless %}
{% endblock form_label %}
{% block form_row %}
{% spaceless %}
{{ form_widget(form) }}
{{ form_errors(form) }}
{% endspaceless %}
{% endblock form_row %}
{% block submit_row %}
{% spaceless %}
<div class="col-12">
{{ form_widget(form) }}
</div>
{% endspaceless %}
{% endblock submit_row %}
{% block text_widget %}
{% spaceless %}
<div class="col-12">
<div>
{{ form_label(form) }}
</div>
{{ form_widget(form) }}
</div>
{% endspaceless %}
{% endblock text_widget %}
{% block choice_widget %}
{% spaceless %}
<span>
{{ form_label(form) }}
{% if expanded %}
{{ block('choice_widget_expanded') }}
{% else %}
{{ block('choice_widget_collapsed') }}
{% endif %}
{{ form_errors(form) }}
</span>
{% endspaceless %}
{% endblock choice_widget %}
In case you get stuck somewhere ;)
We use to do it this way (when we want custom rendering).
First, we extend the FormType :
namespace App\Form\Extension;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
class FormTypeExtension extends AbstractTypeExtension
{
public function getExtendedType()
{
return FormType::class;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefault('main_title', false);
$resolver->setAllowedTypes('main_title', 'boolean');
}
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['main_title'] = $options['main_title'];
}
}
Think to register you extension in Symfony !
Then you can use it in your form builder this way :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add(
'myField',
TextType::class,
array(
'main_title' => true
));
}
Finally, in your template :
{% block form_row -%}
{% spaceless %}
{% if main_title %}
<h2>{{ form_label(form) }}</h2>
{% else %}
{{ form_label(form) }}
{{ form_widget(form) }}
{% endif %}
{% endspaceless %}
{%- endblock form_row %}
Feel free to override that block with your needs ;-)

Flash message in symfony 3.4

I'm trying to set flash message from ContactAction then redirect on Homepage, but on it, I can't see my flash message, maybe my session is reset ? Can I have some help, I'm a beginer on Symfony.
CoreController that contain both index and contact functions :
<?php
namespace OC\CoreBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class CoreController extends Controller
{
public function indexAction()
{
$ServiceAdverts = $this->container->get('oc_core.listAdverts');
$adList = $ServiceAdverts->getListAdverts();
return $this->render("OCCoreBundle:Core:index.html.twig", array(
'listAdverts' => $adList
));
}
public function contactAction()
{
$this->addFlash('info', 'Contact page not ready yet !');
return $this->redirectToRoute('oc_core_homepage');
}
}
Twig template (homepage) :
{% block body %}
<div>
Messages flash :
{% for msg in app.session.flashBag.get('info') %}
<div class="alert alert-success">
{{ msg }}
</div>
{% endfor %}
</div>
<h2>Liste des annonces</h2>
<ul>
{% for advert in listAdverts %}
<li>
<a href="{{ path('oc_platform_view', {'id': advert.id}) }}">
{{ advert.title }}
</a>
par {{ advert.author }},
le {{ advert.date|date('d/m/Y') }}
</li>
{% else %}
<li>Pas (encore !) d'annonces</li>
{% endfor %}
</ul>
Contact
{% endblock %}
Symfony 3.3 made improvements to flash messages so your Twig template should look different. The app.session.flashBag.get() call is now replaced by app.flashes().
So your Twig code would now be:
{% for msg in app.flashes('success') %}
<div class="alert alert-success">
{{ msg }}
</div>
{% endfor %}
Try this, works for me in 3.2 and 3.4
{% for type, flash_messages in app.session.flashBag.all %}
{% for msg in flash_messages %}
<div class="alert alert-{{ type }}">
{{ msg }}
</div>
{% endfor %}
{% endfor %}
Another thing is that once you called the flashBag it turns empty so you can't use it twice. Check your code that it hasn't been called on another page right before a second redirect ...

Get flash data in template

im try get flashData in a Twig template. In the controller i set:
$session = $this->getRequest()->getSession();
$session->getFlashBag()->add('ok_menu', true);
$session->getFlashBag()->add('msg_menu', 'Las selecciones del menu fueron guardadas correctamente.');
And in the profiler, are displayed:
In the template i write this:
{% if app.session.get('ok_menu') is defined %}
{% if app.session.get('ok_menu') %}
<div class="alert alert-success">
<strong>Éxito:</strong> {{ app.session.get('msg_menu') }}
</div>
{% endif %}
{% endif %}
But, in the page not reder the flash messages.
Any ideas ?.
You probably need to access the values from the flashbag property.
{% if app.session.flashbag.has('ok_menu') %}
{% if app.session.flashbag.get('ok_menu') %}
<div class="alert alert-success">
<strong>Éxito:</strong> {{ app.session.flashbag.get('msg_menu') }}
</div>
{% endif %}
{% endif %}

Error message customization in file upload

Using the guide http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html i'm trying to customize error message, but i've a problem: variable errors is not defined, as we don't validate an entity and we are not calling $this->get('validator')->validate($entity).
{% block field_errors %}
{% spaceless %}
{# errors is undefined here #}
{% endspaceless %}
{% endblock field_errors %}
This is the sample code:
public function uploadAction()
{
$document = new Document();
$form = $this->createFormBuilder($document)
->add('name')
->add('file')
->getForm()
;
if ($this->getRequest()->getMethod() === 'POST') {
$form->bindRequest($this->getRequest());
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($document);
$em->flush();
$this->redirect($this->generateUrl('...'));
}
}
// Variable 'errors' is not assigned
return array('form' => $form->createView());
}
Not sure I understand. If you are following the example then $document has validation rules on it which will be tested by $form->isValid(). {{ form_errors(form) }} should output any errors.
If it is just a template customization question then you need to test for the existence of errors before trying to process them:
{% block field_errors %}
{% spaceless %}
{% if errors|length > 0 %}
<span style="color:red">
{% for error in errors %}
{{ error.messageTemplate|trans(error.messageParameters, 'validators') }}<br />
{% endfor %}
{% endif %}
{% endspaceless %}
{% endblock field_errors %}

Resources