首页 文章

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

提问于
浏览
1

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

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

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

    然后添加此字段以形成并在选项中定义属性名称

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

相关问题