0

I've created a view that shows both the entity itself as well as its linked entities in one view (many-to-many relationship with extra join data).

So far so good. Now I would want for each linked entity to have a delete link/button. This would result the join data in the join table to be deleted.

Quotes have Items. So the jointable is ItemsQuotes. I added a method deleteitem to the Quotes controller and modified the form link in the edit view of Quotes to point to this method.

Now I get an exception that the record could not be found. I've passed the id of the join row and I'm making use of TableRegistry to call get($id) on ItemsQuotes.

I've tried some other things as well (my first idea was to immediately send the delete link to the ItemsQuotes controller but that doesn't seem to work (needing block views?). So what's the proper way of doing cross controller stuff? And what am I doing wrong here?

Thanks in advance.

1 Answers1

0

So I found the answer and would like to share it as it might help someone else.

The key here is that you have to load an additional model otherwise you get an error that you use get() on a boolean.

After this you can use the general way for deleting in a controller:

  • documentation: http://book.cakephp.org/3.0/en/orm/deleting-data.html
  • code (you actually should check if the delete operation worked and act accordingly :) )

    public function deleteItem($id = null) { $this->request->allowMethod(['post', 'deleteitem']); $this->loadModel('ItemsQuotes'); $entity = $this->ItemsQuotes->get($id); $result = $this->ItemsQuotes->delete($entity); return $this->redirect(['action' => 'index']); }

And use a form postLink

At first this seemed to work however it only worked for the last Item (as the form was ended already there).

The documentation mentions my error above:

If you want to use this method inside of an existing form, you must use the block option so that the new form is being set to a view block that can be rendered outside of the main form.

The cookbook is pretty vague on this but this SO question shows it nicely for how to do this in Cakephp2 and cakephp3: How to use FormHelper::postLink() inside of a form?

echo $this->Form->postLink(
    'Delete',
    [
        'action' => 'delete',
        $attendanceid
    ],
    [
        'block' => true, // disable inline form creation
        'class' => 'btn btn-dark btn-sm col-md-4',
        'confirm' => __('Are you sure you want to delete')
    ]
);

Cheers

Community
  • 1
  • 1