0

为了在表单字段中设置默认值symfony2,我使用了rel结合 jQuery 的属性,如下所示

    $builder->add('title', 'text', array(
        'attr'=> array(
            'class'=>'prepopulate',
            'rel'=>'Enter a title here...',
        )
    ));

这完美地工作并提供以下内容:


在此处输入图像描述


如您所见,该字段预先填充了“在此处输入标题...”。如果我按原样验证表单,则不会在插入默认值时进行验证(这是有道理的)。

我想确保用户自定义此字段并且不只是提交具有默认值的表单...

有没有办法检查该字段是否与 rel 属性的值相同?

4

2 回答 2

1

嗯……

您可以在实体的注释中尝试此操作:

@Assert\Regex("/^(?!Enter a title here\.\.\.)/")

甚至更好:

/**
 * @Assert\Regex(
 *     pattern="/^Enter a title here\.\.\.$/",
 *     match=false,
 *     message="Please enter a title."
 * )
 */
于 2012-11-14T06:37:24.057 回答
1

我们可以在客户端执行此操作,并将 rel 属性与提交的数据进行比较。如果值相同,我们清除对象:

$(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; 
    });
});
于 2012-11-14T08:36:32.030 回答