How to override the form validation messages in symfony2. Though there is a validation.xml file related model classes. I think it validates a form based on html5.
"Please match the requested format", "Please fill out this field". Is there any way to override this validation messages.
Please help me in this regard, i am stuck for more than a day, as i am totally new to symfony
Those messages you see are HTML5 validation messages which are created by the browser. If you want to override them you need to add an oninvalid attribute to the input tag associated with that field. You can do this in two ways:
In your controller or form type, add this attribute to the form field:
$builder->add('email', 'email',array(
'attr'=>array('oninvalid'=>"setCustomValidity('Would you please enter a valid email?')")
));
Or, in your twig template, add this attribute when rendering the form field:
{{ form_row(form.email, { 'attr': {'oninvalid': "setCustomValidity('Please give me a nice email')"} }) }}
You can change the message of each validator thanks to the message option when declaring the assert:
/**
* #ORM\Column(type="string", length=255, unique=true)
* #Assert\NotBlank(
* message="You have to choose a username (this is my custom validation message).",
* groups={"registration", "account", "oauth"}
* )
Also you can apply translation by creating the file MyBundle/Resources/translations/validators.fr.xliff
Related
I have a form with a collection subform inside. In the subform, there is a choiceType field for the attribute "resourceId". Its data are populated by ajax, with Select2 js plugin (because its data depends on another choice, in which you select the resource type).
In the specific case that i have already a value in resourceId choice, i can't validate my field :
transformationFailure: TransformationFailedException {#4328 ▼
#message: "Unable to reverse value for property path "resourceId": The choice "bd922d35fb828da6e39edf3c7927511c9a6be025" does not exist or is not unique"
This is due because i have to add the default value of the field by javascript (thanks Select2).
I need to cancel the validation on the field, but even if i use the ResetViewTransformers() in the BuildForm method and by rebuilding the field in the PreSubmit event, it still doesn't validate.
TL;DR : How can i cancel validation during PreSubmit event ? (only on my field if possible)
Found the solution. I was going in the wrong direction.
All i had to do was overriding the ChoiceType class and disable the ViewTransformers, then use the new class :
class NonTransformedChoiceType extends ChoiceType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder->resetModelTransformers();
$builder->resetViewTransformers();
}
}
add some jquery and add the .ignore class to your specific form field. If you load whole form i suggest loading them seperately so that way you can easily add it.
$("#myform").validate({
ignore: ".ignore, :hidden"
})
Hidden will also make sure that any fields you do hide, for other reason will not be affacted and then give errors, reference: here
I wrote a very simple extension in typo3 v7.6.11 with the extension builder where a visitor can ask for a taxi-ride.
everything works, only that I need to make the request more appealing by asking the pick-up point and the drop-off point ... that request goes to the actual form like this in the template (requestPid is the id of the page with the form):
<f:form pageUid="{settings.additional.requestPid}" action="form" name="request" object="{Request}">
<f:render partial="Ticket/RequestNewFields" />
<f:form.submit value="{f:translate(key: 'tx_wmnltickets_domain_model_ticket.admin.continue')}" />
</f:form>
but the formAction in the controler doesn't actually ask anything from the model (getArguments() I tried);
/**
* action form
*
* #return void
*/
public function formAction() {
$this->request->getArguments();
}
the request does send the $_POST but I see no way to get it into the form ...
if you'd like to see more code to understand, just ask, I don't know what you'd be looking for ...
Your form action should has the request parameter from you form:
/**
* action form
*
* #param array $request
*
* #return void
*/
public function formAction($request) {
}
Then you can access the data with $request['origin']
I'm not sure if the variable $request is allowed as argument. Maybe you must rename it in the function and in your fluid template if it doesn't work.
Did you create the extension with the builder? The easiest way is to create the fields (pickup-point, dropoff-point) in the builder, then create a createAction or newAction (not sure how it is called in the builder). It will create the template for the createAction where you can just copy/paste the <f:form...
There is a way to access directly POST/GET parameters (It is not recomended to use it directly when you can make it with the clean extbase way):
$myVar = \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('myVar');
When I render a form, form Filed Name is given as an array. For example: search[item], search[keyword] etc. where search is name of the form.
I'm not great on working with forms but I think, the name should be rendered as simply, name="item" or name="keyword".
I've looked at all the documentation, customizing form rendering topic etc. but I can't find any way to change the default behaviour of Symfony form to render form filed name from 'search[item]' to 'item'.
This way, when I ask for the POST data, I can ask simply $this->getRequest()->request->get('item'), as I have to deal with lots of individual parameters.
Help would be great i) To figure out how to achieve what I want. ii) to let me know, why the name is rendered this way. is this the good practice?
Rather than accessing parameters from the Request object, you can bind the Request object to the form.
For example, in your controller method that you post your form to:
namespace Acme\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Acme\Form\MyFormClass;
class MyFormController extends Controller
{
receiveFormAction(Request $request)
{
$form = new MyFormClass();
// you can specify that a route only accepts a post
// request in the routing definition
if ($request->isMethod('POST')) {
// this populates the form object with the data
// from the form submission
$form->bind($request);
if ( ! $form->isValid()) {
throw new \Exception('Invalid form');
}
// an array of the data the format you require
$data = $form->getData();
$data['item'];
$data['keyword'];
// etc.
}
}
}
The above is the way you should be handling forms in Symfony 2, and is how you can leverage the power that the forms component gives you, with validation etc.
Symfony supports multiple forms on a page. They might be instances of the same form or have similar field names. Having the fields for each form all together in an array makes this easy to do.
I'm using the form::select helper in Kohana 3.2 to generate a select input with the following code (formatted for display here):
form::select('id_plyta', $plyta, $plyta_selected,
array('style' => 'width:300px', 'class' => 'sock_depend'));
This code generates the following HTML (formatted for display here):
<select name="id_plyta" class="sock_depend" style="width:300px"
multiple="multiple">
...
</select>
The problem is that it is outputting with an extra multiple="multiple" attribute in the HTML. I don't want that to be a part of it.
If I put a NULL instead of $plyta_selected then it works fine.
How do I get rid of multiple="multiple" and why is it even there?
When you check out the list of parameters it accepts, pay attention to the third:
* #param string input name
* #param array available options
* #param mixed selected option string, or an array of selected options
* #param array html attributes
When sending the paramters to the select method of the Form class, if the third parameter is an array, the helper will automatically include the multiple="multiple" to allow it to pre-select more than one option in the drop down select.
If you only send a string value, then it will not create a multibox, will not include the multiple HTML input attribute and it will only pre-select the single value.
I want to create a Symfony 2 Form for a Blog Post. One of the fields that I am wondering how might I implement is the tags field. Post has a many-to-many relationship with Tag. I want my Form to have 1 text box where users enter in a comma separated list of tags. Which will then be converted into multiple Tag's.
How should I implement it? Do I:
Have a tagsInput field (named differently from in the Entity where $tags should be an ArrayCollection)
On POST, I split the tags and create/get multiple tags. Then validate the tags (eg. MaxLength of 32)
I think you are already on the right way since I saw your other question about the form type. I will just comfort you with your choice.
A form type is probably the best way to go. With the form type, you will be able to display a single text field in your form. You will also be able to transform the data into a string for display to the user and to an ArrayCollection to set it in your model. For this, you use a DataTransformer exactly as you are doing in your other question.
With this technique, you don't need an extra field tagsInput in your model, you can have only a single field named tags that will an ArrayCollection. Having one field is possible because the you form type will transform that data from a string to an ArrayCollection.
For the validation, I think you could use the Choice validator. This validator directive seems to be able to validate that an array does not have less than a number of item and not more than another number. You can check the documentation for it here. You would use it like this:
// src/Acme/BlogBundle/Entity/Author.php
use Symfony\Component\Validator\Constraints as Assert;
class Post
{
/**
* #Assert\Choice(min = 1, max = 32)
*/
protected $tags;
}
If it does not work or not as intended, what you could do is to create a custom validator. This validator will then be put in your model for the tags field. This validator would validate the an array have a maximum number of element no greater than a fixed number (32 in your case).
Hope this helps.
Regards,
Matt