Field specific errors on repeated field - php

I am required to display errors under specific fields depending on the situation. In my case there can be two. Which are Password is empty and Passwords do not match. Currently all the messages gets displayed under the password.second field.
I need to display Password is empty error under the password.first field and Passwords don not match under the password.second field.
I tried to generate the errors separately via {% for error in form.password.first.vars.errors %} and {% for error in form.password.second.vars.errors %} but failed as the two error messages I require only gets rendered when I use {% for error in form.password.vars.errors %}. I have been at this for quite a while and returned empty handed. The implementation is as follows,
I am using a repeated field to implement the password and confirm password as follows,
$builder->add( 'password', 'repeated', array( 'type' => 'password','required' => true, 'invalid_message' => ErrorMessages::PASSWORDS_DO_NOT_MATCH, 'options' => array('attr' => array('class' => 'password-field form-control')),'first_options' => array('label' => false,'error_bubbling' => true,'label_attr'=>array('class'=>'col-sm-4 control-label')),'second_options' => array('label' => false,'label_attr'=>array('class'=>'col-sm-4 control-label'))));
And the password entity validation is as follows,
class User implements UserInterface, \Serializable {
/**
* #Assert\Email(message=ErrorMessages::EMAIL_ADDRESS_INVALID)
* #Assert\NotBlank(message=ErrorMessages::EMAIL_ADDRESS_EMPTY)
*/
private $email;
/**
* #Assert\NotBlank(message=ErrorMessages::PASSWORD_EMPTY, groups={"full"})
*/
private $password;
....
I render these two fields in the twig in the following manner,
<div class="form-group {% if form.password.vars.errors|length > 0 %}has-error{% endif %} {% if form.password.vars.required == 'true' %}required{% endif %}">
{{ form_label(form.password.first, "Password") }}
<div class="col-sm-8">
{{ form_row(form.password.first) }}
</div>
</div>
<div class="form-group {% if form.password.vars.errors|length > 0 %}has-error{% endif %} {% if form.password.vars.required == 'true' %}required{% endif %}">
{{ form_label(form.password.second, "Confirm password") }}
<div class="col-sm-8">
{{ form_row(form.password.second) }}
<span class="help-block">
{% for error in form.password.vars.errors %}
{{ error.messageTemplate|trans(error.messageParameters, 'validators')~'' }}
{% endfor %}
</span>
</div>
</div>

If you want to use the convenient repeated field, then you're probably stuck - the way repeated works is to duplicate, using a ValueToDuplicatesTransformer, the field you add into two fields containing the same data, and it ensures that they are the same at the point where the Transformer turns submitted form values back into model data (not using normal constraints). From validation's PoV, there is only one field, so you can't choose which textbox the error goes against.
But there may be other options if you want to sort it out yourself!
You could make a Custom Validation Constraint. To achieve the behaviour you're after I think you'll need it to be a Class Constraint Validator, so that it has access to both fields at once, and can compare them. However, that will again mean that the error gets applied at a higher level than you want, so probably won't work.
So probably the way is to manually test the fields in your Controller, and add the relevant error directly to the field with which you want it to be associated, something like the following. You need to split the password field into two so that you can test them against each other, so put the NotBlank constraint on the first field.
Controller
// ...
$password1 = $form->get('password1');
$password2 = $form->get('password2');
if ($password1->getData() != $password2->getData() )
{
$password2->addError(new FormError("Passwords do not match!") );
}
// ...

Related

Symfony Sonata Admin - add field type url in listView not working

i'm trying to add a field type url in the list view of an entity, this is the link at the documentation -> https://symfony.com/doc/master/bundles/SonataAdminBundle/reference/field_types.html#url .
This is my code, i've simply copied the documentation:
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('name')
->add('url', 'url', [
'url' => 'http://example.com'
]);
}
This seems to work but the column "Url" is always empty.
I found the template of Sonata that is responsible to render this field -> #SonataAdmin/CRUD/list_url.html.twig .
Here is the code
{% extends get_admin_template('base_list_field', admin.code) %}
{% block field %}
{% spaceless %}
{% if value is empty %}
{% else %}
{% if field_description.options.url is defined %}
...
The problem is that value is always empty, i don't know what is this variable; and the documentation is not talking about any field named value.
So you can achieve this by creating a template which simply contains a button with the URL you'd like to link to. See below:
First we define a field on the list view which references a template, the type is null:
->add('foo', null, [
'template' => 'example/foobar.html.twig',
])
Inside our template we've just referenced, we can do the following:
{% extends '#SonataAdmin/CRUD/base_list_field.html.twig' %}
{% block field %}
<a class="btn btn-success" href="http://google.co.uk/">My Link</a>
{% endblock %}
and now you should see the button display as a column on the list view.
It would be nice if the documented suggestion worked as intended, this solution is a work around.

How to make sure that a Symfony form does not contain unnecessary elements?

I am a beginner in Symfony, so this question might be simple for those who are more experienced in this framework.
I am building forms and I have several possible types of items in forms. At this moment these are:
text
html
image
However, in the future there will be many more items. Previously, the project generated all items into their place (text, html and image) and hidden those which are not needed for the specific form item (maximum one is needed). However, I intend to avoid adding items I do not need. Since I do not know at the point buildForm of an arbitrary item is running whether it is text, html or image, so at this point all of them are added (I know this is counter-intuitive, but this is a code I try to refactor):
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('layoutTypeInput', TextType::class);
$builder->add('blockTypeOutput', EntityType::class, array(
'class' => 'MyPageBundle:BlockTypeOutput',
'choice_label' => 'titleHu',
'required' => false,
'placeholder' => 'Válassz blokk kimenetet!',
'empty_data' => null,
));
$builder->add('text', TextType::class, $this->getBlockTypeOptions('text'));
$builder->add('html', TextareaType::class, $this->getBlockTypeOptions('html'));
$builder->add('image', ImageSelectType::class, $this->getBlockTypeOptions('image'));
$builder->addEventListener(FormEvents::POST_SET_DATA, array($this, 'onPostSetData'));
$builder->addEventListener(FormEvents::PRE_SUBMIT, array($this, 'onPreSubmit'));
}
Now, I have a function which removes the unnecessary elements of a form:
private function removeUnnecessaryItems(\Symfony\Component\Form\FormInterface $form, $key)
{
$keys = ['text', 'html', 'image'];
foreach ($keys as $k) {
if ($key !== $k) $form->remove($k);
}
}
And inside onPostSetData I call it like this:
$this->removeUnnecessaryItems($form, $inputObject->getLayoutTypeIdText());
and finally, in the twig I determine what should be generated into the form:
{% for ioLayoutBlock in form.ioLayoutBlocks %}
<div class="row">
<div class="col-xs-12 col-md-3">
{{ form_errors(ioLayoutBlock.layoutTypeInput) }}
{{ioLayoutBlock.layoutTypeInput.vars.label}}
</div>
{{ form_widget(ioLayoutBlock.layoutTypeInput, {'attr' : {'class':'hidden'}}) }}
<div class="col-xs-12 col-sm-6 col-md-5">
{{ form_errors(ioLayoutBlock.blockTypeOutput) }}
{{ form_widget(ioLayoutBlock.blockTypeOutput, {'attr' : {'class':'blockTypeOutput'}}) }}
</div>
<div class="col-xs-12 col-sm-6 col-md-4">
{% if ioLayoutBlock.text is defined %}
{{ form_errors(ioLayoutBlock.text) }}
{{ form_widget(ioLayoutBlock.text, {'attr':{'class':'hidden uniqueInput ioLayoutBlock_text' }}) }}
{% elseif ioLayoutBlock.html is defined %}
{{ form_errors(ioLayoutBlock.html) }}
{% if layout.layoutType.name == 'userHTML' %}
<div class="input-group ioLayoutBlock_html hidden">
<a class="input-group-addon myAdminForm" target="_blank" data-my-href="page/{{ page.id }}/wysiwyg/{{ layout.id }}"><span class="glyphicon glyphicon-pencil"></span></a>
{{ form_widget(ioLayoutBlock.html, {'attr':{'class':'uniqueInput wysiwyg' }}) }}
</div>
{% else %}
{{ form_widget(ioLayoutBlock.html, {'attr':{'class':'hidden uniqueInput wysiwyg ioLayoutBlock_html' }}) }}
{% endif %}
{% elseif ioLayoutBlock.image is defined %}
{{ form_errors(ioLayoutBlock.image) }}
{{ form_widget(ioLayoutBlock.image, {'attr':{'class':'hidden uniqueInput ioLayoutBlock_image' }}) }}
{% endif %}
</div>
</div>
{% endfor %}
and if I load the page, everything is shown correctly, but unfortunately, when I try to submit the form, it gives the error of
This form should not contain extra fields.
as many times as many form items I have. If I comment out the call on removeUnnecessaryItems inside onPostSetData and subsequently remove the conditionals from the twig, like:
{% if ioLayoutBlock.text is defined %}
then everything works, but that's how it worked before the refactor. Ideally I would like to avoid adding so many unnecessary things at buildForm, but I do not know how can I load up any meaningful data there to determine the type of the item. Alternatively I would like to ensure that the items are successfully removed at the events where I do know their type, without the form errors on submit I described above. So, my question is: How can I avoid generating all kinds of unnecessary stuff into my form without being blocked by submit errors?
My approach would be to give a parameter to your form
$form = $this->createForm(DynamicType::class, $user, [
'layout_type_id' => $layoutTypeIdText,
]),
Then adds the fields depending of the param
public function buildForm(FormBuilderInterface $builder, array $options)
{
$this->layout_type = $options['LayoutTypeId'];
// [...]
if ($this->layout_type !== 'text' )
$builder->add('text', TextType::class, $this->getBlockTypeOptions('text'));
// [...]
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
// [...]
'layout_type_id' => null,
]);
}
With this approch, the good part is you don't to duplicate your logic in twig, the form get the fields it needs, so you can just render the form using
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
For your specific case you need to avoid adding the items at buildForm, to handle the default empty values at onPreSubmit (as the transformers will not be called if the items are not added at buildForm) and to add the effective items at onPreSubmit.
You were correct using form listeners, they are the way to go for your use case.
I see 2 sub scenarii:
the form data is coming from the Model, you fill it inside the controller
a new item is added to the form, client-side (via the prototype).
I'm getting from your example code that users can't add new items dynamically. If you want to do so, the code is just slightly different.
Remains the first scenario. The trick is not to remove, but to add forms inside the PRE_SET_DATA listener:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('layoutTypeInput', TextType::class);
$builder->add('blockTypeOutput', EntityType::class, array(
'class' => 'MyPageBundle:BlockTypeOutput',
'choice_label' => 'titleHu',
'required' => false,
'placeholder' => 'Válassz blokk kimenetet!',
'empty_data' => null,
));
$builder->addEventListener(FormEvents:: PRE_SET_DATA, array($this, 'onPreSetData'));
// ...
}
public function onPreSetData(FormEvent $event)
{
$data = $event->getData(); // This contains model data (ie., from controller)
$form = $event->getForm();
$type = 'image'; // Read type from your model
$formType = $this->getFormTypeForType($type);
$builder->add($type, formType, $this->getBlockTypeOptions($type));
}
private function getFormTypeForType($type)
{
switch ($type) {
case 'image':
return ImageSelectType::class;
// ...
default:
// Up to you, you can decide on setting a default type or enforcing that the type is correct
throw new \RuntimeException('Unsupported type');
}
}
With that code, you can keep the same Twig.
I'm not sure on what you are trying to do with layoutTypeInput and blockTypeOutput. Maybe we are answering just partially here, don't hesitate on posting the full use case.

Nested collections in forms

I tried to follow this answer to handle nested collections in forms.
I have an Application's Form with a collection of LienAppliServ's Form :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('servLiens', 'collection', array(
'label' => ' ',
'type' => new LienAppliServType(),
'allow_add' => true,
'allow_delete' => true,
'by_reference' =>false,
'prototype' => true,
))
//...
In my LienAppliServ's Form, I have another collection of PortLienAppliServ's Form :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('ports', 'collection', array(
'type' => new PortLienAppliServType(),
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'by_reference' =>false
))
//...
And the form of PortLienAppliServ is :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('numPort')
->add('type')
;
}
Now, I'd like to handle add/delete for each collection...
As I said, I tried to follow this answer
In order to do that, I tried :
{% block body -%}
{{ form_start(form) }}
<ul id="col-servliens" data-prototype="{{ form_widget(form.servLiens.vars.prototype)|e }}">
{# iterate over each existing tag and render its only field: name #}
{% for servLiens in form.servLiens %}
<li>{{ form_row(servLiens) }} </li>
<ul id="col-ports" data-prototype="{{ form_widget(ports.vars.prototype)|e }}">
{%for ports in servLiens.ports %}
<li>{{ form_row(ports) }}</li>
{% endfor %}
{% endfor %}
</ul>
{{ form_end(form) }}
{% endblock %}
{% block app_js %}
//Same as the other question
<script>
function FormCollection(div_id)
{
// keep reference to self in all child functions
var self=this;
self.construct = function () {
// set some shortcuts
self.div = $('#'+div_id);
self.div.data('index', self.div.find(':input').length);
// add delete link to existing children
self.div.children().each(function() {
self.addDeleteLink($(this));
});
// add click event to the Add new button
self.div.next().on('click', function(e) {
// prevent the link from creating a "#" on the URL
e.preventDefault();
// add a new tag form (see next code block)
self.addNew();
});
};
/**
* onClick event handler -- adds a new input
*/
self.addNew = function () {
// Get the data-prototype explained earlier
var prototype = self.div.data('prototype');
// get the new index
var index = self.div.data('index');
// Replace '__name__' in the prototype's HTML to
// instead be a number based on how many items we have
var newForm = prototype.replace(/__name__/g, index);
// increase the index with one for the next item
self.div.data('index', index + 1);
// Display the form in the page in an li, before the "Add a tag" link li
self.div.append($(newForm));
// add a delete link to the new form
self.addDeleteLink( $(self.div.children(':last-child')[0]) );
// not a very nice intergration.. but when creating stuff that has help icons,
// the popovers will not automatically be instantiated
//initHelpPopovers();
return $(newForm);
};
/**
* add Delete icon after input
* #param Element row
*/
self.addDeleteLink = function (row) {
var $removeFormA = $('<i class="entypo-trash"></i>');
$(row).find('select').after($removeFormA);
row.append($removeFormA);
$removeFormA.on('click', function(e) {
// prevent the link from creating a "#" on the URL
e.preventDefault();
// remove the li for the tag form
row.remove();
});
};
self.construct();
}
</script>
<script>
$(document).ready(function() {
new FormCollection('col-servliens');
new FormCollection('col-ports');
});
</script>
And I get
Variable "ports" does not exist.
I really need some help.. Collections are actually my nightmare...
Thanks !
Let me start with apologies, because my answer in the post you mention was clearly wrong :) At least the example code was incorrect. I wonder if the original poster ever found the right solution.
The error is easy enough to spot. In the Twig you use the variable ports, but how should Twig know where it comes from?
{% for servLiens in form.servLiens %}
<li>{{ form_row(servLiens) }} </li>
<ul id="col-ports" data-prototype="{{ form_widget(ports.vars.prototype)|e }}">
{%for ports in servLiens.ports %}
<li>{{ form_row(ports) }}</li>
{% endfor %}
{% endfor %}
Using {{ form_row(servLiens) }} will actually already create the collection classes, so the whole <ul> inside it is not needed. In fact Symfony is smart enough that you don't even need the first <ul>. It will find any child forms (ex. collections) and create all the HTML needed.
So the only thing you need to have in your code is:
{{ form_row(form.servLiens) }}
If you would look at the HTML generated from that, you will see the data-prototype and the children. It will automatically have an id attribute that you can use.
Problem is the javascript part. You are using a collection within a collection. The javascript FormCollection class (which I wrote) cannot handle this as simply as you've tried it. It will handle the top collection fine, but it will not automatically instantiate collections on load/create/delete. Remember that each servLiens collection has a collection of ports. Therefore already at loading you can't simply load the col-ports as you do now, but would need to load each port collection. Then you'd need to instantiate a new FormCollection on the port collection every time you add a servLiens row.
I don't have time to create your code for you, but I hope my explanation helps you to find a solution.
Looks like you use symfony 2.6 or older.
I would start by saying you should'nt do "'type' => new PortLienAppliServType()" but pass the form type name. Symfony will instantiate it and it could be the problem.
Everything is described in extend here: https://symfony.com/doc/2.6/reference/forms/types/collection.html#basic-usage
Honestly, Collections are not that difficult you just need to understand how it works then Symfony will manage everything for you.

Symfony - Form item as plain text

I have a form that contains a collection of forms (a Vote with many VoteChoice). The VoteChoiceType is as follows
class VoteChoiceType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('answer', null, array('disabled' => true))
->add('priority', null);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'PollBundle\Entity\VoteChoice',
));
}
}
Now in my Controller I create and populate many VoteChoices, setting the answer according to the available choices for the current poll (derived from the URL)
$vote = new Vote();
$vote->setPoll($poll);
foreach ($vote->getPoll()->getPollOptions() as $op) {
$vc = New VoteChoice();
$vote->addVoteChoice($vc->setAnswer($op));
}
So when the Form loads, I want all the options to display only - not to be an actual choice, and then the user can set the priority they want. However, the answer is of every single answer I have in my poll_options table (each Poll has many PollOption, similar to how each Vote has many VoteChoice)
Current twig template
<ul class="voteChoices" data-prototype="{{ form_widget(form.voteChoices.vars.prototype)|e('html_attr') }}">
{% for voteChoice in form.voteChoices %}
<li>{{ form_row(voteChoice.answer) }} {{ form_row(voteChoice.priority) }}</li>
{% endfor %}
</ul>
</div>
<p><button type="submit" class="btn btn-success">Go!</button></p>
{{ form_end(form) }}
I want the voteChoice.answer as a plain text (so it's not part of a dropdown - I know I can disable it in the FormBuilder, but I don't want it to appear as part of a drop-down menu, I just want it as plain text)
If I use voteChoice.answer I get the following symfony error
An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class Symfony\Component\Form\FormView could not be converted to string") in poll\vote.html.twig at line 9.
I have a __toString function in my VoteChoice class.
I want the voteChoice.answer as a plain text (so it's not part of a dropdown - I know I can disable it in the FormBuilder, but I don't want it to appear as part of a drop-down menu, I just want it as plain text)
You can access the current data of your form via form.vars.value (Reference):
{{ voteChoice.vars.value.answer }}
This means that voteChoice.vars.value is an instance of PollBundle\Entity\VoteChoice so you can remove the answer field from your form safely if this is not required by edit.

Symfony2 Twig Iterator

I have form $form, which have text field for each entity User.
$form = $this->createFormBuilder();
$form->add('users', 'collection');
foreach ($query->getResult() as $user)
{
$form->get('users')->add($user->getName(), 'text', array('data' => $user->getName()));
}
I need to access specific input form by its ID number. So i have to be able to do something like this:
{{ form_widget(form.users[0]) }}
But it doesn't work. I can't use this:
{% for user in form.users %}
I need to access text fields specificly by their id's
Found the solution.
{% set interator = form.users.iterator %}
{{ interator.seek(0) }}
{{ form_widget(interator.current) }}

Categories