2011-12-16 53 views
1

我需要创建字段,作为选项获取正则表达式字符串。Symfony2 - 正则表达式验证

所以,我提出PatternType字段:

public function getDefaultOptions(array $options) 
{ 

    $defaultOptions = array(
     'data'    => null, 
     'data_class'  => null, 
     'trim'    => true, 
     'required'   => true, 
     'read_only'   => false, 
     'max_length'  => null, 
     'pattern'   => null, 
     'property_path'  => null, 
     'by_reference'  => true, 
     'error_bubbling' => false, 
     'regexp'   => false, 
     'error_mapping'  => array(), 
     'label'    => null, 
     'attr'    => array(), 
     'invalid_message' => 'This value is not valid', 
     'invalid_message_parameters' => array() 
    ); 

    $class = isset($options['data_class']) ? $options['data_class'] : null; 

    // If no data class is set explicitly and an object is passed as data, 
    // use the class of that object as data class 
    if (!$class && isset($options['data']) && is_object($options['data'])) { 
     $defaultOptions['data_class'] = $class = get_class($options['data']); 
    } 

    if ($class) { 
     $defaultOptions['empty_data'] = function() use ($class) { 
      return new $class(); 
     }; 
    } else { 
     $defaultOptions['empty_data'] = ''; 
    } 


    $patt = $options['regexp']; 

    unset($options['regexp']); 

    $defaultOptions['validation_constraint'] = new Regex(
                 array(
                  'pattern' => $patt, 
                  'match' => true, 
                  'message' => 'Niewłaściwy format' 
                  ) 
                 ); 


    var_dump($defaultOptions); 


    return $defaultOptions; 
} 

的var_dump返回井格式化设置数组,内regex对象 - 但是当产生形式验证不起作用 - 传递任何值。任何想法为什么?

回答

1

你为什么这样做?已有regex validator。只需使用该验证器的普通文本字段。

如果您需要一个没有模型类绑定的表单,请阅读the corresponding section

+0

我已经完成了上述操作:创建了一个字段,它扩展了抽象类型,并返回了带有validator_constant = new Regex(params)的默认选项数组。 – McOffsky 2011-12-17 13:45:57

0

好吧,我发现什么是错的 - 你只能将验证常量添加到根形式对象(其他symfony简单地忽略)。所以看来,我需要的仅仅是获取根形式,添加validator_constant和validator_group选项集。然后只分配字段适当的validator_group。