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

Set form data from controller in CakePHP 3

我的应用程序中有一个登录表单。在某些情况下,我想从控制器传递数据。

表单是这样创建的:

<?= $this->Form->create(null, ['url' => ['controller' => 'Users', 'action' => 'login']]); ?>
<?= $this->Form->input('email', ['label' => __('E-mail')]); ?>
<?= $this->Form->input('password', array('label' => __('Password'))); ?>

在控制器中,我想为 email 字段修复一个默认值,但是在 set 多次尝试后,request->data,等等...找不到怎么做。

    $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';

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

您可以使用实体而不是直接访问 $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';

If data is already comes from the form and you want to modify data before post.

$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']);  
}