Forms 在CakePHP 3中从控制器设置表单数据

Forms 在CakePHP 3中从控制器设置表单数据,forms,cakephp-3.0,Forms,Cakephp 3.0,我的申请表中有一个登录表单。在某些情况下,我希望从控制器传递数据 表单的创建方式如下: <?= $this->Form->create(null, ['url' => ['controller' => 'Users', 'action' => 'login']]); ?> <?= $this->Form->input('email', ['label' => __('E-mail')]); ?> <?= $this-&

我的申请表中有一个登录表单。在某些情况下,我希望从控制器传递数据

表单的创建方式如下:

<?= $this->Form->create(null, ['url' => ['controller' => 'Users', 'action' => 'login']]); ?>
<?= $this->Form->input('email', ['label' => __('E-mail')]); ?>
<?= $this->Form->input('password', array('label' => __('Password'))); ?>
在CakePHP2中,这只需简单地在
$this->request->data
上编写

$this->request->data['User']['email'] = 'whatever';

请注意,登录表单显示为一个元素,因此它可以在应用程序视图中的任何位置重用。

您可以使用实体,而不是直接访问
$this->request->data
数组

请尝试以下脚本:

//declare a new entity of user
$user = $this->Users->newEntity();

//set the default data
$user->email = 'whatever@domain.com';
$user->username = 'whatever name';

//set the entity to the view vars
$this->set(compact('user'));
更新:


您也可以使用这一行:
$this->request->data['email']='which'

而不是:
$this->request->data['User']['email']='which'

如果数据已经来自表单,并且您希望在发布前修改数据


尝试使用
$this->request->data['email']='user@example.net';可能这是我唯一没有尝试的东西:)它工作得很好!。这个问题。同时,我尝试了不同的选项,我也更改了表单,因为CakePHP-3表单创建与Cake2有点不同。始终是您最后尝试的:)我在前面的代码中尝试过它,但是当您使用带有数据数组的newEntity进行初始化时,它会验证表单,因此它会将错误传递给表单(需要密码):
$this->set('user',$this->Accounts->Users->newEntity(['email'=>'whatever']));
。您的解决方案对我有效,但只需要创建一个新实体来将一个数据传递给表单帮助器。问题是:这比使用
$this->request->data
更正确吗?您可以使用实体或
$this->request->data
。我更新了答案,您必须在不使用
'User'
键的情况下设置数据nk这一切都取决于你如何在模板中声明de form。现在我使用这个
,你提供的两个解决方案都有效。请注意,我必须注意,
$user
尚未设置,因为登录表单可能是应用程序中任何位置的一个元素,并且控制器可能尚未设置该变量。
$this->request->data['email']='随便什么';
救了我的命谢谢
//declare a new entity of user
$user = $this->Users->newEntity();

//set the default data
$user->email = 'whatever@domain.com';
$user->username = 'whatever name';

//set the entity to the view vars
$this->set(compact('user'));
$myData = $this->myData->newEntity();    
$this->request->data['field_name'] = "value";  
pr($this->request->getData());  // for display whole form data with changed data
$myData = $this->myData->patchEntity($myData, $this->request->getData());  
if ($this->myData->save($myData)) {  
    $this->Flash->success(__('Data has been saved.'));  
    return $this->redirect(['action' => 'index']);  
}