Why param disapperer from url after save a post and error? Cake php 2

I would like to know the reason why the param pass (in this case the post id) is lost and this error is returned. I’m going crazy with so many things I’ve tried and it doesn’t work, and I’m feeling like it’s some simple mistake…

The error:

Notice (8): Undefined offset: 0 [APP/Controller/PostsController.php, line 65]
Code Context
            // O dono de um post pode editá-lo e deletá-lo

            if (in_array($this->request->action, array('edit', 'delete'))) {

                $postId = (int) $this->request->params['pass'][0];
$user = array(
	'id' => (int) 48,
	'username' => 'adm',
	'role' => 'admin',
	'created' => '2022-01-20 15:28:24',
	'modified' => '2022-01-20 15:28:24'
)
PostsController::isAuthorized() - APP/Controller/PostsController.php, line 65
ControllerAuthorize::authorize() - CORE/Cake/Controller/Component/Auth/ControllerAuthorize.php, line 63
AuthComponent::isAuthorized() - CORE/Cake/Controller/Component/AuthComponent.php, line 470
AuthComponent::startup() - CORE/Cake/Controller/Component/AuthComponent.php, line 311
ObjectCollection::trigger() - CORE/Cake/Utility/ObjectCollection.php, line 129
CakeEventManager::dispatch() - CORE/Cake/Event/CakeEventManager.php, line 244
Controller::startupProcess() - CORE/Cake/Controller/Controller.php, line 683
Dispatcher::_invoke() - CORE/Cake/Routing/Dispatcher.php, line 189
Dispatcher::dispatch() - CORE/Cake/Routing/Dispatcher.php, line 167
[main] - APP/webroot/index.php, line 117

My Post controller and view, respectively:



<?php
// File: /app/Controller/PostsController.php

App::uses('AppController', 'Controller');

class PostsController extends AppController {
    public $helpers = array ('Html','Form');
    public $name = 'Posts';

    public function index(){
        //$this->autoRender = false;


    }
    public function list() {
        $this->set('list', $this->Post->find('all'));
    }

    public function view($id = null) {
        $this->set('post', $this->Post->findById($id));
    }
    public function add() {
        if ($this->request->is('post')) {
            $this->request->data['Post']['user_id'] = $this->Auth->user('id'); // Adicionada essa linha
            if ($this->Post->save($this->request->data)) {
                $this->Flash->success('Your post has been saved.');
                $this->redirect(array('action' => 'list'));
            }
        }
    }

    public function edit($id = null) {
        
        // Campo do id recebe id do post atual
        $this->Post->id = $id;
        if ($this->request->is('get')) {
            // var_dump($this->request->data);
            $this->request->data = $this->Post->findById($id);
        } else {
            // var_dump($this->request->data);
            if ($this->Post->save($this->request->data)) {
                $this->Flash->success('Seu Post foi atualizado.');
                $this->redirect(array('action' => 'list'));
            }
        }
    }

    public function delete($id) {
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        if ($this->Post->delete($id)) {
            $this->Flash->success('O post com o id: ' . $id . ' foi excluído.');
            $this->redirect(array('action' => 'list'));
        }
    }

    public function isAuthorized($user) {
        if (parent::isAuthorized($user)){
            // Todos os usuários registrados podem criar posts
            if ($this->action === 'add') {
                return true;
            }
            // O dono de um post pode editá-lo e deletá-lo
            if (in_array($this->request->action, array('edit', 'delete'))) {
                $postId = (int) $this->request->params['pass'][0];
                return $this->Post->isOwnedBy($postId, $user['id']);
            }
        }
    }
}
?>
<!-- File: /app/View/Posts/edit.ctp -->

<h1>Edit Post</h1>
<?php
    echo $this->Form->create('Post', array('url' => 'edit'));
    echo $this->Form->input('title');
    echo $this->Form->input('body', array('rows' => '3'));
    echo $this->Form->input('id', array('type' => 'hidden'));
    echo $this->Form->end('Save Post');

You get that notice because $this->request->params['pass'] is empty at that spot.
So you should check

if(isset($this->request->params['pass'][0]){

}

I can’t tell your how/where that pass request param should be set (especially in CakePHP 2) so I guess you expect pass to always have some value even though it doesn’ t.

1 Like

Thanks for reply KevinPfeifer,

The param is passed in url when i click on link of edit posts, the post id is passed as param, i have access to edit title and body of post usually, even alterations are saved, but this error yet ocurrs.

Url example: http://localhost:8888/posts/edit/27
“27” is the id of a post

What does debug($this->request->params) give you if you try it right before the line that gives the error?

1 Like

Thanks for reply, Zuluru

Debug returns the following before save the post:

/Controller/PostsController.php (line 65)
array(
	'plugin' => null,
	'controller' => 'posts',
	'action' => 'edit',
	'named' => array(),
	'pass' => array(
		(int) 0 => '27'
	)
)

And the following after save the post:

/Controller/PostsController.php (line 65)
array(
	'plugin' => null,
	'controller' => 'posts',
	'action' => 'edit',
	'named' => array(),
	'pass' => array()
)

If help, here is the edit view code:

<!-- File: /app/View/Posts/edit.ctp -->

<h1>Edit Post</h1>
<?php
    echo $this->Form->create('Post', array('url' => 'edit'));
    echo $this->Form->input('title');
    echo $this->Form->input('body', array('rows' => '3'));
    echo $this->Form->input('id', array('type' => 'hidden'));
    echo $this->Form->end('Save Post');

Here’s your issue. You are telling it that you want to post to a URL that does not include your ID in it.

1 Like

Thank you so much Zuluru s2, I was looking the solution in the middle and ending of logical, even learn about add url but i don’t searched in edit view. I lost around one week trying solve this problem :frowning: , but thanks to your help I will also fix the following problems at the beginning of the streams ^^