How to get the link id present in the postLink method?

2

I need to get the id of the link present in the postLink method to be able to delete an image whose id is equal to that id of the link, which is equal to the id of the database. How do I get this value?

View

    <h2>Apagar Fotografia</h2>
   <br>
   <table border="1" bordercolor="#e2e2e2"  width="720" style="word-wrap: break-word">
   <tr>
    <?php
        $i=0;
        foreach( $gallery_images as $gallery_image ):?>

        <?php
            echo "<td style=text-align: justify>";
            //echo $gallery_image['GalleryImage']['path'];
            echo $this->Form->postLink('Apagar Fotografia', array('controller'=>'Gallery', 'action'=>'admin_del_image', $gallery_image['GalleryImage']['id'],/*'prefix'=>'admin'*/), array('class'=>'foto_del', 'title'=>'Apagar Fotografia'), __('Tem a certeza que quer apagar esta Fotografia?'));
            echo "</td>";
            echo "<td>";
            //$src3 =$this->webroot. 'img/gallery/' .$gallery_image['GalleryImage']['path'];
            echo $this->Html->image('gallery/' . $gallery_image['GalleryImage']['path'] , array('width' => '200px', 'height' => '133px', 'alt' => $gallery_image['GalleryImage']['path'] )); 
            echo "</td>";
            $i++;
            if($i==2){
                echo "</tr><tr>";
                $i=0;   
            }
        ?>
        <?php endforeach ?>
</tr>

Controller

    public function admin_del_image(){
        $this->layout = 'admin_index';
        $this->loadModel('GalleryImage');
        $this->GalleryImage->id=$id;

        $gallery_images = $this->GalleryImage->find('all');
        $this->set('gallery_images', $gallery_images);

        if($this->request->is('post')){

        if(!$this->GalleryImage->exists()){
            throw new NotFoundException(__('Fotografia inválida'));
        }
        //$this->request->onlyAllow('post','delete');

        $options = array('conditions' => array('GalleryImage.' .$this->GalleryImage->primaryKey=>$id));
        $gallery_image_delete=$this->GalleryImage->find('first', $options);

        if(file_exists(WWW_ROOT. "img/gallery/" .$gallery_image_delete['GalleryImage']['path'])){
            unlink(WWW_ROOT . "img/gallery/" .$gallery_image_delete['GalleryImage']['path']);
            $this->GalleryImage->delete();
            $this->Session->setFlash(__('Fotografia excluída com sucesso'));
        }
        else{
            $this->Session-setFlash(__('ERRO!, esta Fotografia não existe'));
        }
        $this->redirect($this->refere());}
 }

Output

    <td style="text-align:" justify=""><form action="/html/PushUp_app/Gallery/admin_del_image/25" name="post_5330531636e39982291469" id="post_5330531636e39982291469" style="display:none;" method="post"><input type="hidden" name="_method" value="POST"></form><a href="#" class="foto_del" title="Apagar Fotografia" onclick="if (confirm(&quot;Tem a certeza que quer apagar esta Fotografia?&quot;)) { document.post_5330531636e39982291469.submit(); } event.returnValue = false; return false;">Apagar Fotografia</a></td>
    <td><img src="/html/PushUp_app/img/gallery/PushUp.png" width="200px" height="133px" alt="PushUp.png"></td>
    
asked by anonymous 21.03.2014 / 18:52

1 answer

1

Doubt

Is your controller called Gallery ? But do you want to delete a GalleryImage ?

Here we have two options:

  • Or your controller should be changed to Galleries
  • Or you should create a controller GalleryImages

Anyway, I say this just to follow good practices.

Your postLink is incorrect

echo $this->Form->postLink(
  $gallery_image['GalleryImage']['path'],
  array(
    'controller' =>'Gallery',
    'action'=>'admin_del_image'
  ),
  array(
    'id'=> $gallery_image['GalleryImage']['id']
  ),
  "tem a certeza que quer apagar esta Fotografia?");

In your case, you passed the link id as the GalleryImage id . And with that, your action will not be able to proceed with the request. (Or maybe you have treated otherwise, which is not described in the question ...)

The correct one should be:

<?php echo $this->Form->postLink(
  'Excluir Imagem',
  array(
    'action' => 'del_image',
    $gallery_image['GalleryImage']['id'],
    'prefix' => 'admin'
  ),
  array(
    'class' => 'classe-que-voce-deseja',
    'title' => 'Excluir Imagem'
  ),
  __('Tem certeza que deseja excluir este registro?')); ?>

Change your action

Follow the template below ( do not need to use the exact code I've done, it's just a template for you to have a base ):

/**
 * admin_del_image method
 *
 * @throws NotFoundException     
 */
public function admin_del_image($id)
{

  // Como não sei qual model você está usando, pois o nome
  // do controller é diferente, não vou fazer o loadModel() aqui

  // Seta o id e verifica se a imagem existe
  $this->GalleryImage->id = $id;
  if (!$this->GalleryImage->exists()) {
    throw new NotFoundException(__('Image inválida'));
  }

  // valida se a requisição foi feita por POST ou DELETE (method)
  // caso contrário retorna MethodNotAllowed
  $this->request->onlyAllow('post', 'delete');

  // Configura as opções para buscar pela imagem (first = limit 1)
  $options = array('conditions' => array('GalleryImage.' . $this->GalleryImage->primaryKey => $id));
  $galleryImage = $this->GalleryImage->find('first', $options);

  // Verifica se a imagem existe no diretório especificado
  if(file_exists(WWW_ROOT . "diretorio-da-sua-imagem-aqui/" . $galleryImage['GalleryImage']['path'])) {

    // exclui a imagem
    unlink(WWW_ROOT . "diretorio-da-sua-imagem-aqui/" . $galleryImage['GalleryImage']['path']);

    // exclui o registro
    $this->GalleryImage->delete();

    // mensagem da sessão
    $this->Session->setFlash(__('Imagem excluída com sucesso'));

  } else {

    // Se não encontrou a imagem no disco, retorna a mensagem de erro
    $this->Session->setFlash(__('Esta imagem não existe'));

  }

  // Redireciona para a página anterior
  $this->redirect($this->referer());

}

[EDIT]

As for the error described in the comments, it is your action and due to the absence of $id .

In this case, your action looks like this:

public function admin_del_image(){

But it should look like this:

public function admin_del_image($id){

I hope I have helped.

Any questions, leave a comment below.

    
21.03.2014 / 20:27