CakePHP以某种方式两次保存相同的数据。出于某种原因,我想实现这个add方法,这样$dummy就会在有人直接进入domain.com/recordings/add
时立即保存。
它看起来很直,我一直在挠我的头。我检查了验证错误;我尝试禁用验证;我尝试使用patchEntity()
代替。
不过,奇怪的是,如果通过单击domain.com/recordings/add
中的add recording
按钮(而不是在浏览器上键入url ),数据只保存一次。
主计长:
public function add()
{
$dummy = [
"user_id" => 1,
"title" => "tgfbthgdthb",
"body" => "rgcvfghfhdxcgb",
"published" => 0,
];
$recording = $this->Recordings->newEntity($dummy);
$this->Recordings->save($recording);
}
模式/表格:
public function initialize(array $config): void
{
parent::initialize($config);
$this->setTable('recordings');
$this->setDisplayField('title');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER',
]);
$this->hasMany('Words', [
'foreignKey' => 'recording_id',
]);
}
模式/实体:
protected $_accessible = [
'user_id' => true,
'title' => true,
// 'slug' => true,
'body' => true,
'published' => true,
'created' => true,
'modified' => true,
'user' => true,
'words' => true,
];
意见:
<?php
/**
* @var \App\View\AppView $this
* @var \App\Model\Entity\Recording $recording
*/
?>
<div class="row">
<aside class="column">
<div class="side-nav">
<h4 class="heading"><?= __('Actions') ?></h4>
<?= $this->Html->link(__('List Recordings'), ['action' => 'index'], ['class' => 'side-nav-item']) ?>
</div>
</aside>
<div class="column-responsive column-80">
<div class="recordings form content">
<?= $this->Form->create($recording) ?>
<fieldset>
<legend><?= __('Add Recording') ?></legend>
<?php
echo $this->Form->control('user_id', ['options' => $users]);
echo $this->Form->control('title');
echo $this->Form->control('body');
echo $this->Form->control('published');
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
</div>
</div>
发布于 2020-08-24 14:24:23
不要试图适应人们的懒散,不允许他们仅仅通过访问一个GET
请求来保存数据,这只会带来麻烦,而且这是糟糕的应用程序设计。
至少实现一个只为POST
请求保存数据的适当的安全措施。
浏览器可能在各种情况下发出多个请求,从飞行前的OPTIONS
请求到奇怪的怪癖,例如,如果在响应数据的前x字节中找不到任何编码信息,火狐就中止请求,然后发出一个新请求,该请求假定响应的特定编码。
public function add()
{
if ($this->request->is('post')) {
// save data here
}
}
https://stackoverflow.com/questions/63554874
复制相似问题