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

时间:2013-07-24 10:40:25

标签: symfony symfony-forms symfony-2.3

Workaround:现在将父母从形式转换为文本就可以了。

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

有没有人知道我怎样才能获得正确的property_path?我的意思是,在MyFieldType中,我想访问MyFormType的属性,该属性使用了my_field_type字段,因此我可以使用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';
        }
    }

先谢谢了,

1 个答案:

答案 0 :(得分:0)

您可以在选项中传递它。首先在自定义字段中设置默认值

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

然后添加此字段以形成并在选项

中定义属性名称
->add('some_name', 'color_palette', array('property_name' => 'some_name'));
相关问题