2015-06-22 24 views
1

我想将请求数据传递给此表单类以验证通用信息。我已经实现了一个组件(外包了可重用性)以将地址数据转换为所需的模型格式。使用表单中的组件

namespace App\Form; 

use Cake\Form\Form; 
use Cake\Form\Schema; 
use Cake\Validation\Validator; 

class Foo extends Form { 
    protected function _buildSchema(Schema $schema) { 
     return $schema 
        ->addField('foo', 'string') 
        ->addField('bar', 'string'); 
    } 
    [...] 
    protected function _execute(array $data) { 
     // How is it possible to use component-method here? 
     // e.g. $this->MyAddressComponent->saveData($data); 
     return true; 
    } 
} 

有没有人知道我要做什么?

在此先感谢!

+1

你最有可能不应该做一个表格需要的组件,组件用于控制器,并且引入这种依赖性可能会使测试更加复杂。为了让别人给你一个适当的建议,如果你能分享更多的上下文,也就是说它是什么功能,为什么控制器以及表单需要它等等,这将是一件好事,等等...... – ndm

+0

查看更新的问题 –

+0

你可以将你的视图设置为$ this-> view-> form = new Foo();在你的控制器中做某件事。而当我写这个答案时,我意识到我正在表达与第一个评论相同的内容。 – Blkc

回答

1

让您的形式接受该组件在构造函数中:

namespace App\Form; 

use App\Controller\Component\MyAddressComponent; 

class Foo extends Form { 

    private $addressComponent; 

    public function __constructor(MyAddressComponent $addressComponent) 
    { 
     $this->addressComponenent = $addressComponent; 
    } 

    ... 

    protected function _execute(array $data) { 
     $this->addressComponent->saveData($data); 
     return true; 
    } 
} 

然后从控制器实例如下形式:

public function doStuff() 
{ 
    $form = new Foo($this->MyAddressComponent); 
    ... 
} 
相关问题