2016-03-01 84 views
2

我有以下实体领域:断言正则表达式和TypeGuessing

/**  
* @Assert\Regex(
* pattern = "/^d+\.(jpg|png|gif)$/", 
* htmlPattern = "/^d+\.(jpg|png|gif)$/" 
*) 
**/ 

protected $src; 

形式由这样的创建:

$builder 
    ->add('src', TextareaType::class, array(//neither is TextType::class working 
     'attr' => array('class' => 'mysrc'), 
)); //pattern will not be rendered 

的问题是,只要我提供的字段类型类TextareaType::class正则表达式模式未呈现为表单的约束。或换句话说:如果字段类型被猜测,则只呈现正则表达式模式:

$builder 
    ->add('src', null, array( 
     'attr' => array('class' => 'mysrc'), 
)); //pattern will be rendered 

任何解决方法?我想在一个地方,即在我的实体中,而不是在一个控制器或一个表单中有正则表达式模式。

回答

3

叶普,这是它应该如何工作。不仅字段类型被猜测,而且一些选项也是如此,如果类型没有被猜测出选项。

顺便说一句,textarea元素不支持pattern属性,但是如果你想添加一个:'attr' => array('pattern' => '/jsregex/'),你应该为客户端使用与服务器端不同的模式。如果你想在一个地方使用constant

+1

实际上,symfony会在'TextareaType'附加'pattern'属性,但只有当类型被猜测时,由于不受支持的属性,它是无效的。由于类型猜测和手动类型定义之间的差异,还有一个验证问题。有趣的问题。 – chalasr

+0

Thx的信息。我很好,如果模式只传递,即使它不受textarea支持。并且问题依然存在于'TextType'中 – musicman

+1

如果你想要或者使用'Column(type =“text”)'',你可以将它作为属性选项传递给它,并且它将被猜成textarea。 – 1ed

1

也许这一个可以帮助你:

FormType

use Symfony\Component\Form\Extension\Core\Type\TextType; 
use Symfony\Component\Validator\Validator\ValidatorInterface; 
use Symfony\Component\Validator\Constraints\Regex; 
use YourBundle\Entity\YourEntity; 

public function __construct(ValidatorInterface $validator) 
{ 
    $this->validator = $validator; 
} 

public function getRegexPattern($property) 
{ 
    $pattern = null; 
    $metadata = $this->validator->getMetadataFor(new YourEntity()); 
    $propertyMetadata = $metadata->getPropertyMetadata($property); 
    $constraints = $propertyMetadata[0]->constraints; 

    foreach($constraints as $constraint) { 
     if ($constraint instanceof Regex) { 
      $pattern = $constraint->pattern; 
     } 
    } 

    return $pattern; 
} 

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder->add('src', TextType::class, array(
     'attr' => array(
      'class' => 'mysrc', 
      'pattern' => $this->getRegexPattern('src') 
     ), 
    )); 
} 

services.yml(所需注入式验证)

services: 
    app.form.type.your_entity_type: 
     class: YourBundle\Form\YourEntityType 
     arguments: 
      validator: "@validator" 
     tags: 
      - { name: form.type } 

渲染

<input type="text" pattern="/^d+\.(jpg|png|gif)$/" class="src"/> 

像这样,即使手动设置了TextType,您也会通过从属性约束中检索到的模式获得html验证。