我有3个文件:
第一个:
public function register(\Pimple\Container $app)
{
$app['manager.form'] = function() use ($app) {
return new Form($app);
};
}
第二
class Form
{
private $form;
public function __construct(Application $app)
{
$this->form = $app['form.factory']->createBuilder(FormType::class);
}
public function addDuree()
{
$this->form->add('duree', ChoiceType::class, [
'choices' => [
'1' => '1',
'3' => '3',
'6' => '6',
'12' => '12'
],
'multiple' => false,
'expanded' => true,
'data' => 1
]);
}
public function addPaiementType()
{
$this->form->add('paiementType', ChoiceType::class, [
'choices' => [
'virement' => 'virement',
'cheque' => 'cheque',
'paypal' => 'paypal',
'paypal-cb' => 'paypal-cb'
],
'multiple' => false,
'expanded' => true,
'data' => 'virement'
]);
}
public function addTermsAccepted()
{
$this->form->add('termsAccepted', CheckboxType::class, [
'mapped' => false,
'constraints' => new Assert\IsTrue(),
]);
}
public function getForm()
{
return $this->form->getForm();
}
}
控制器:
$form = $app['manager.form']->addDuree()->addPaiementType()->addTermsAccepted();
但是Silex给了我错误:
Call to a member function addPaiementType() on null
我不明白为什么。对我来说,这个代码结构相当于:
$form = $app['form.factory']->createBuilder(FormType::class)
->add('duree', ChoiceType::class, [
'choices' => [
'1' => '1',
'3' => '3',
'6' => '6',
'12' => '12'
],
'multiple' => false,
'expanded' => true,
'data' => 1
])
->add('paiementType', ChoiceType::class, [
'choices' => [
'virement' => 'virement',
'cheque' => 'cheque',
'paypal' => 'paypal',
'paypal-cb' => 'paypal-cb'
],
'multiple' => false,
'expanded' => true,
'data' => 'virement'
])
->add('termsAccepted', CheckboxType::class, [
'mapped' => false,
'constraints' => new Assert\IsTrue(),
])
->getForm();
但似乎不是......不知道为什么。
感谢您的帮助
答案 0 :(得分:2)
要使用对象调用链接,方法必须返回$this
。你不是那样做的。您的addDuree()
根本没有否 return
,因此它含有return null
,这意味着这一行:
$form = $app['manager.form']->addDuree()->addPaiementType()->addTermsAccepted();
执行就好像写了
$form = $app['manager.form']->null->addPaiementType()
^^^^
你应该
function addPaimentType() {
... stuff ...
return $this;
}