After I add a herd
to the system, the user gets redirected to the herdimports
controller where he can enter the import data.
I would like to have the add and edit form in one action and view.
In the controller it works:
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'));
}
In the view I have the following code:
<?= $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() ?>
Which works perfect when I have entries for that herd. But if there are now entries yet (the add case), then the foreach
is ignored.
How can I check in the view if there are rows or not. I've tried $herdimport->count()
, but that gives errors when there are no rows.
Also tried $herdimport->isNew()
, which gives an error when there are rows.
Any ideas?
You probably shouldn't do this:
$herdimport = $this->Herdimports->newEntity();
If you want to add/edit multiple items, then $herdimport
should always be either a query, or a list of entities, not a single entity.
If the underlying goal/problem is to have an initial set of inputs in case there are no records yet, then you could do something like this:
$entity = $this->Herdimports->newEntity();
$entity->herd_id = $herd_id;
$herdimport = [$entity];
ie simply wrap the initial entity in an array (and make sure that you populate the foreign key field).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.