Reputation: 31919
To set a default value in a form field in symfony2
, I use the rel
attribute combined with jQuery as beautifully explained here:
$builder->add('title', 'text', array(
'attr'=> array(
'class'=>'prepopulate',
'rel'=>'Enter a title here...',
)
));
This works perfectly and gives the following:
As you can see, the field is pre-populated with "Enter a title here...". If I validate the form as it is, validation does not take place as a default value is inserted (which makes sense).
I want to make sure the user customizes this field and does not just submit the form with the default value...
Upvotes: 0
Views: 341
Reputation: 31919
We can do this on the client side, and compare the rel attribute with the submitted data. If the value is the same, we clear the object:
$(function() {
// When we submit the form
$('form').submit(function() {
//iterate over all the elements of the class "prepopulate"
jQuery('.prepopulate').each(function(){
//compare the values submitted vs rel attribute
if( jQuery(this).val() == jQuery(this).attr('rel'))
jQuery(this).val('');
});
return true;
});
});
Upvotes: 1
Reputation: 2811
Hmmm...
You could try this in your entity's annotation:
@Assert\Regex("/^(?!Enter a title here\.\.\.)/")
or even better:
/**
* @Assert\Regex(
* pattern="/^Enter a title here\.\.\.$/",
* match=false,
* message="Please enter a title."
* )
*/
Upvotes: 1