在自定义字段类型中获取property_path

问题描述:

Workaround:现在,将表单父窗口从窗体转换为文本可以实现这一功能。在自定义字段类型中获取property_path

我刚刚创建了一个父类型为form的自定义字段类型。

是否有人知道我如何得到正确的property_path?我的意思是,在MyFieldType内部,我想访问使用my_field_type字段的MyFormType属性,这样我就可以通过dinamically设置正确的property_path。

这是我的自定义字段类型。在下面的类中,想要将使用ColorPaletteField的表单类型属性设置为propery_path值。

 


    namespace WE\BobbyWebAppBundle\Form\Field; 

    use Symfony\Component\Form\AbstractType; 
    use Symfony\Component\Form\FormView; 
    use Symfony\Component\Form\FormInterface; 
    use Symfony\Component\OptionsResolver\OptionsResolverInterface; 
    use Symfony\Component\PropertyAccess\PropertyAccess; 
    use Symfony\Component\Form\FormBuilderInterface; 
    use Symfony\Component\Form\Extension\Core\EventListener\TrimListener; 

    class ColorPaletteField extends AbstractType 
    { 
     public function setDefaultOptions(OptionsResolverInterface $resolver) 
     { 
      $resolver->setDefaults(array(
        'mapped'   => true, 
        'error_bubbling' => false, 
        'colors'   => array() 
       ) 
      ); 
     } 

     /** 
     * Pass the help to the view 
     * 
     * @param FormView $view 
     * @param FormInterface $form 
     * @param array $options 
     */ 
     public function buildView(FormView $view, FormInterface $form, array $options) 
     { 
      $parentData = $form->getParent()->getData(); 

      if(null !== $parentData) 
      { 
       $accessor  = PropertyAccess::getPropertyAccessor(); 
       $defaultColor = $accessor->getValue($parentData, 'calendar_color'); 
      } 
      else { $defaultColor = null; } 

      if(array_key_exists('colors', $options)) 
      { 
       $colors = $options[ 'colors' ]; 
      } 
      else { $colors = array(); } 

      $view->vars[ 'colors' ]   = $colors; 
      $view->vars[ 'defaultColor' ] = $defaultColor; 
     } 

     public function getParent() 
     { 
      return 'form'; 
     } 

     public function getName() 
     { 
      return 'color_palette'; 
     } 
    } 

在先进的感谢,

+0

请我们看一些代码示例 – 2013-07-24 10:50:31

+0

我刚刚编辑和暴露出的使用上面的代码。谢谢。 – user846226

你可以通过它的选项。在自定义字段第一套默认

$resolver->setDefaults(array(
    'mapped'   => true, 
    'error_bubbling' => false, 
    'colors'   => array() 
    'property_name'  => 'calendar_color' 
)); 

然后添加此领域形成并把它定义在选择属性名

->add('some_name', 'color_palette', array('property_name' => 'some_name')); 
+0

谢谢forgottenbas,我已经想过你提出的解决方法,但我正在寻找一个真正的,整洁的解决方案。现在我改变了父母从形式到文本,并做了诀窍。 – user846226