BIOS
BIOS

Reputation: 1695

Passing data from a view to a different views controller in Cakephp

I have a form displayed for editing values already saved to a database. One of the values is an image (in the form of a relative file path). I want to create a link within the form to display the image in a separate view when clicked.

My question is what is the best way to pass this view's (edit view) image field data to the controller of the view that will display the image independently?

I would rather not do it via the url.

Upvotes: 1

Views: 1732

Answers (1)

joshua.paling
joshua.paling

Reputation: 13952

Pass the ID of the record you're editing. Then in your controller, you'd have a function like view_image($id) which fetches the images relative path from the database, based on the $id field passed in.

Then you can display the image however you want in the view_image.ctp view file.

UPDATE:

First and formeost, the question is why don't you want to include the ID in the URL? Sometimes people feel insecure about showing ID's publicly, but in most cases, there's no problem with it at all.

Anyway, assuming you have a legitimate need not to include the ID in the URL, the other way to do it would be to pass the id (or the image path for that matter) in via POST, rather than in the URL (GET). You know the difference? GET includes the parameters in the URL, where as POST wraps them up in the request itself, so they're not in the URL.

If you want an example of doing this, CakePHP does it in the case of it's default Delete functions and links that get generated by the Bake console.

In the case of deleting a record, here's an example of a POST link in the view:

echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $product['Product']['id']),array('class'=>'delete'), __('Are you sure you want to delete %s?', $product['Product']['list_title']));

And the example controller method looks like this:

public function admin_delete($id = null) {
    if (!$this->request->is('post')) {
        throw new MethodNotAllowedException();
    }
    $this->Product->id = $id;
    if (!$this->Product->exists()) {
        throw new NotFoundException(__('Invalid product'));
    }
    if ($this->Product->delete()) {
        $this->Session->setFlash(__('Product deleted'));
        $this->redirect(array('action' => 'index'));
    }
    $this->Session->setFlash(__('Product was not deleted'));
    $this->redirect(array('action' => 'index'));
}

So you shouldn't find it too hard to adapt that for your own purposes.

Upvotes: 2

Related Questions