我有以下表格:
class TestFormType extends AbstractType
{
protected $testArgument;
public function buildForm(FormBuilderInterface $builder, array $options)
{
if (isset($options['testArgument'])) {
$this->testArgument = $options['testArgument'];
}
$builder->add('textField', 'Symfony\Component\Form\Extension\Core\Type\TextType');
}
public function configureOptions(OptionsResolver $optionsResolver)
{
$optionsResolver->setRequired('testArgument');
$optionsResolver->setDefaults(
array(
'data_class' => get_class($this->testArgument)
)
);
}
}
我通过表单选项(Symfony 3修改)传递testArgument
属性的值,但是什么时候获取属性的类名来设置'data_class'
里面configureOptions
方法,始终是null
。基本上我需要依赖于configureOptions
方法中的表单类型类属性。有人可以帮我在这里找到正确的方向吗?
答案 0 :(得分:0)
我必须从表单工厂create
方法本身传递$form = $this->factory->create(
'app\TestBundle\Form\Type\TestFormType',
$this->testArgument,
array(
'data_class' => get_class($this->testArgument)
)
);
方法中的依赖项:
class TestFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('textField', 'Symfony\Component\Form\Extension\Core\Type\TextType');
}
}
因为它不会被表单类型中的默认设置设置,并且必须重构表单类型类,如下所示:
# function returning a decorator, takes arguments
def message(param1, param2):
# this does the actual heavy lifting of decorating the class
# this function takes a class and returns a class
def wrapper(wrapped):
# we inherit from the class we're wrapping (wrapped)
# so that methods defined on this class are still present
# in the decorated "output" class
class WrappedClass(wrapped):
def __init__(self):
self.param1 = param1
self.param2 = param2
# call the parent initializer last in case it does initialization work
super(WrappedClass, self).__init__()
# the method we want to define
def get_message(self):
return "message %s %s" % (self.param1, self.param2)
return WrappedClass
return wrapper
@message("param1", "param2")
class Pizza(object):
def __init__(self):
pass
pizza_with_message = Pizza()
# prints "message param1 param2"
print pizza_with_message.get_message()
答案 1 :(得分:0)
您应将* Type __constructor传递给
use App\Entity\Blog; use Symfony\Component\Form\AbstractType; use Symfony\Component\OptionsResolver\OptionsResolver;
class BlogType extends AbstractType {
private $someDependency;
public function __construct($someDependency)
{
$this->someDependency = $someDependency;
}
// ...
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'empty_data' => new Blog($this->someDependency),
]);
} }