I'm trying to get a form validated but its behavior is strange, I'm a newbie in symfony2 so I must be missing something.
I use SonataAdminBundle to create forms and CRUD controller. My ResponsableDato entity has this property:
/**
* #var string $contacto
* #Assert\NotBlank(message="Please enter your name.")
* #Assert\Length(min="3", minMessage="too short."))
* #ORM\Column(name="contacto", type="string", length=100, nullable=true)
*/
private $contacto;
If I leave contacto field blank it gives me "Complete this field" message instead of "Please enter your name". If I type one character it passes NotBlank validation but ignores Length validation.
What could I be missing? It sounds as if I had to override something to get it to work
also you're talking about html5 validation or isValid() to form_errors() case?
i'm quite sure that "Complete this field" is related to "required" option in your form field
$builder->add('contacto', 'text', array('required' => false));
set required to false and see your custom error message :)
edit:
use Symfony\Component\Validator\Constraints as Assert;
[...]
/**
* #Assert\NotNull()
*/
private $contacto;
this will fire validation error after submit, though if there's no data for this field in the form, if you need to avoid an empty string use #Assert\NotBlank()
Related
I made an extension with the Extension Builder in Typo3 6.2 using Fluid 6.2 and Extbase 6.2.
I made Appointment-Objects with a date property.
I want to enter the date in the format "dd.mm.yyyy".
So I tried this:
And it gives this error:
I'm clueless as I'm not familiar with this and I want to solve this in a nice way.
My createAction code is simply generated by the extension builder and therefore looks like this:
/**
* action create
*
* #param \JH\Appmgmt\Domain\Model\Appointment $newAppointment
* #return void
*/
public function createAction(\JH\Appmgmt\Domain\Model\Appointment $newAppointment) {
$this->addFlashMessage('The object was created. Please be aware that this action is publicly accessible unless you implement an access check. See Wiki', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::ERROR);
$this->appointmentRepository->add($newAppointment);
$this->redirect('list');
}
Now I realize that if I change something here in order for the format to work I would have to do the same thing in the updateAction and maybe others that I don't know about yet.
I also desperately tried to format it to the desired format somehow in the partial but that was bound to fail - same result:
<f:form.textfield property="appointmentDate" value="{appointment.appointmentDate->f:format.date(format:'Y-m-d\TH:i:sP')}" /><br />
So that's where I need your help - I don't know where and how to globally allow this date format since I will be needing it for other fields as well.
The only other thing I can think of is changing something in the domain model:
/**
* appointmentDate
*
* #var \DateTime
*/
protected $appointmentDate = NULL;
but I don't know how I should approach this. :(
Anyone an idea?
You send a date that is not formatted correctly as a date Object.
that's exactly what the error says.
What you can do is re-format the date you send so that it arrives at your controller action as a valid argument for your object. this is done with an initialize action that invokes a property mapping.
a clear example can be found here:
http://www.kalpatech.in/blog/detail/article/typo3-extbase-datetime-property-converter.html
the part that you need is:
// Here we convert the property mapping using the property mapper
public function initializeAction() {
if ($this->arguments->hasArgument('newCalendar')) {
$this->arguments->getArgument('newCalendar')->getPropertyMappingConfiguration()->forProperty('startdate')->setTypeConverterOption('TYPO3\\CMS\\Extbase\\Property\\TypeConverter\\DateTimeConverter',\TYPO3\CMS\Extbase\Property\TypeConverter\DateTimeConverter::CONFIGURATION_DATE_FORMAT,'d-m-Y');
}
}
You could also disable the validation of the date arguments to your controller and create a valid date Object from your 'date' and then use setAppointmentDate($yourNewDateObject).
You then go round the extbase validation, what is not a good practise.
Got everything in my form validating using i18n just fine but cant figure out how to translate the form validation. For example right now when I try and submit the form with an empty field I get the pop-up validation message "Please fill out this field."
Translation is turned on and annotations enabled:
// config_dev.yml
framework:
router:
resource: "%kernel.root_dir%/config/routing_dev.yml"
strict_requirements: true
profiler: { only_exceptions: false }
translator: { fallback: en }
validation: { enable_annotations: true }
Entity is rigged for validation annotations:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
....
/**
* #var string
* #Assert\NotBlank(message = "Custom validation error message")
* #ORM\Column(name="url", type="string", length=512)
*/
private $url;
I also created the file validators.en.yml in my app/Resources/translations folder but not sure where to go from here. Can anyone help?
You could translate validation messages in app/Resources/translations/validators.fr.xlf (example for french xlf translation file)
Here the Docs you are looking for: http://symfony.com/doc/current/validation/translations.html
I want to validate form using asserts in Entity class but when I submit the form, it says $form->isValid() is true.
Here is how I got it setup:
// config.yml
validation: { enabled: true, enable_annotations: false }
// validation.yml
Software\Bundle\Entity\Program:
properties:
name:
- NotBlank: ~
// MyForm
...
$builder
->add('name', 'text', [
'label' => 'word.name'
])
;
...
// Program.php
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, nullable=false)
*/
private $name;
I tried also via Annotations but it did not help.
I know I can put 'constraints' property to my form and there set new NotBlank() but I want to have that validation on Entity level since I am going to use an API and I want to have validation in one place instead of two.
Is my validation.yml file ignored or what?
EDIT
I did not mention one important thing that my form is embedded into another one. in this case you must use 'cascade_validation' property in your form options.
This answer helped me a lot Symfony2 - Validation not working for embedded Form Type
Your configuration seems correct but your yml is ignored, try to clear your cache.
Also where is your validation.yml ? It must be in a path like : src/AppBundle/Resources/config/validation.yml
In your annotation example, there is no validation constraint you must add #Assert\NotBlank on your property. Nullable = false is only for your database schema.
Symfony doc about validation : http://symfony.com/doc/current/cookbook/validation/custom_constraint.html#using-the-new-validator
Same question about using validation.yml : Symfony2 how to load validation.yml
I have an entity set up like this:
use Symfony\Component\Validator\Constraints as Assert;
...
/**
* #var decimal $amount
* #Assert\Currency
* #ORM\Column(name="amount", type="decimal")
*/
private $amount;
If I submit my form with blank in the amount field nothing happens. Shouldn't my form automatically throw an error or what am I missing?
You need a NotBlank assertion (#Assert\NotBlank) to validate that that field wasn't submitted with empty data. If that passes, then your other assertions should run on any actual data submitted.
It's didn't work
array('fio', 'length', 'min'=>5, 'max'=>30, 'message' => 'custom'),
but this work
array('fio, login, password', 'required', 'message' => '{attribute} custom'),
For CStringValidator, there is another property called is which specifies the exact length of a string, and the message property is used only when is property is not satisfied by the input.
Take a look at the source, and this will become clear:
if($this->is!==null && $length!==$this->is)
{
$message=$this->message!==null?$this->message:Yii::t('yii','{attribute} is of the wrong length (should be {length} characters).');
$this->addError($object,$attribute,$message,array('{length}'=>$this->is));
}
For this type of validators:
In addition to the {#link message} property for setting a custom error
message, * CStringValidator has a couple custom error messages you
can set that correspond to different * validation scenarios. For
defining a custom message when the string is too short, * you may
use the {#link tooShort} property. Similarly with {#link tooLong}. The
messages may contain * placeholders that will be replaced with the
actual content. In addition to the "{attribute}" * placeholder,
recognized by all validators (see {#link CValidator}),
CStringValidator allows for the following * placeholders to be
specified: