在我向系统添加herd之后,用户将被重定向到herdimports控制器,在那里他可以输入导入数据。
我希望在一个动作和视图中添加和编辑表单。
在控制器中,它的工作原理是:
public function edit($herd_id = null)
{
if($herd_id == null)
{
// log error
$this->Flash->success(__('No herd was selected.'));
return $this->redirect(['action' => 'index']);
}
$herdimport = $this->Herdimports->find('all')->where(['herd_id'=>$herd_id]);
if($herdimport->count() == 0)
{
$herdimport = $this->Herdimports->newEntity();
}
if ($this->request->is(['patch', 'post', 'put'])) {
$herdimport = $this->Herdimports->patchEntities($herdimport, $this->request->getData());
$this->Herdimports->deleteAll(['herd_id'=>$herd_id]);
if ($this->Herdimports->saveMany($herdimport)) {
$this->Flash->success(__('The herdimport has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The herdimport could not be saved. Please, try again.'));
}
$this->set('herd_id', $herd_id);
$this->set(compact('herdimport'));
}在视图中,我有以下代码:
<?= $this->Form->create($herdimport) ?>
<fieldset>
<legend><?= __('Edit Herdimport') ?></legend>
<? $i = 0; ?>
<? foreach ($herdimport as $h) : ?>
<div class="repeat">
<?= $this->Form->hidden($i.'.herd_id'); ?>
<?= $this->Form->control($i.'.num',['data-default'=>""]); ?>
<?= $this->Form->control($i.'.date',['data-default'=>""]); ?>
<?= $this->Form->control($i.'.origin',['data-default'=>""]);?>
<?= $this->Form->control($i.'.weight',['data-default'=>""]); ?>
<?= $this->Form->control($i.'.price',['data-default'=>""]); ?>
</div>
<? $i ++; ?>
<? endforeach; ?>
<button class="extra-row"><?=__('Extra row');?></button>
<button class="delete-row" style="display: none;"><?=__('Delete row');?></button>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>当我有那群人的参赛作品的时候,效果就很好了。但是,如果现在还没有条目(添加大小写),那么foreach就会被忽略。
如果有行或没有行,如何签入视图。我尝试过$herdimport->count(),但是当没有行时会产生错误。
还尝试了$herdimport->isNew(),它在有行时会出现错误。
有什么想法吗?
发布于 2019-06-18 13:00:03
你也许不该这么做:
$herdimport = $this->Herdimports->newEntity();如果要添加/编辑多个项,则$herdimport应该始终是查询或实体列表,而不是单个实体。
如果根本的目标/问题是在还没有记录的情况下拥有一组初始的输入,那么您可以这样做:
$entity = $this->Herdimports->newEntity();
$entity->herd_id = $herd_id;
$herdimport = [$entity];ie只需将初始实体封装在数组中(并确保填充外键字段)。
https://stackoverflow.com/questions/56648610
复制相似问题