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

Asked

Viewed 219 times

2

I need to get the id link present in the method postLink in order to delete from the database an image id is equal to this link id, which is equal to the database id. How do I get that 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>

1 answer

1


Duvída

Your controller is called Gallery? But you want to delete one GalleryImage?

There are 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 practice.

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 like the id of Galleryimage. And with that, your action will not be able to proceed with the requisition. (Or perhaps you have dealt otherwise, which is not described in the question...)

The correct must 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 model below (you don’t have to use the exact code I made, it’s just a template for you to have a basis):

/**
 * 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 by of its action and by the absence of $id.

In this case, your action is like this:

public function admin_del_image(){

But it should stay that way:

public function admin_del_image($id){

I hope I’ve helped.

Any questions, leave a comment below.

  • I’m sorry to keep you waiting, but I don’t have internet access at home. I have already made several changes to the code, and I have some questions regarding your suggestions. By clicking on the postLink, I get an error Error: The requested address '/html/PushUp_app/Gallery/admin_del_image/25?url=Gallery%2Fadmin_del_image%2F25' was not found on this server., 25 refers to the image id in the database, in addition to the flash message indicating "Invalid photograph", from notFoundException, as if I put the if($this->request->is('post')). No need to assign a value to $id?

  • 1

    @Sunt In this error Cakephp is saying that: there is no in the controller Gallery (that the name is already incorrect), the action admin_del_image. Does it exist? Or not? Or is it in another controller? If it’s in another controller, add to postLink route array() the value: 'controller' => 'GalleryImages'. If you can, create a Gist (gist.github.com) with all the files related to me.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.