我的申请表中有登录表单。在某些情况下,我想从控制器传递数据。
表单以这种方式创建:
<?= $this->Form->create(null, ['url' => ['controller' => 'Users', 'action' => 'login']]); ?>
<?= $this->Form->input('email', ['label' => __('E-mail')]); ?>
<?= $this->Form->input('password', array('label' => __('Password'))); ?>
在控制器中,我想修复电子邮件字段的默认值,但经过多次尝试 set , request-&gt;数据等......无法找到如何做到这一点。
$this->set('email', 'whatever');
$this->set('User.email', 'whatever');
$this->set('user.email', 'whatever');
$this->request->data['user']['email'] = 'whatever';
$this->request->data['User']['email'] = 'whatever';
$this->set('user', $this->Accounts->Users->newEntity(['email' => 'whatever']));
在CakePHP 2中,这只是简单地写在$this->request->data
;
$this->request->data['User']['email'] = 'whatever';
请注意,登录表单显示为元素,因此可以在应用程序视图中的任何位置重复使用。
答案 0 :(得分:1)
您可以使用实体而不是直接访问$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'] = 'whatever';
代替:$this->request->data['User']['email'] = 'whatever';
答案 1 :(得分:0)
如果数据已来自表单,并且您希望在发布之前修改数据。
$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']);
}