Lost Array After Validation Error

Posted by Georges Kmeid on Stack Overflow See other posts from Stack Overflow or by Georges Kmeid
Published on 2012-11-23T10:55:26Z Indexed on 2012/11/23 10:59 UTC
Read the original article Hit count: 253

Filed under:
|

I'm working on a CakePHP project and I have User, Post and Location models among others. User hasMany Location and Post belongsTo User so Location is not directly related to Post.

This is my code in the Post controller:

public function add() {
    if ($this->request->is('get')) {
       $this->loadModel('Location');
       $this->set('locations', $this->Location->find('all', array('conditions' => array('user_id' => $this->Auth->user('id')))));
    }
    ...
}

And this is my code in the posts/add view:

<?php
$i = 0; $j = 0;
foreach ($locations as $location):
    $location_names[$i] = $location['Location']['name'];
    $i++;
endforeach;
echo "<select name=\"location\" onchange=\"select(this.value)\">";
echo "<option value=\"\">Select a saved location</option>";
foreach ($locations as $location):
    echo "<option value=\"" . $location['Location']['latitude'] . "," . $location['Location']['longitude'] . "\">" . $location_names[$j] . "</option>";
    $j++;
endforeach;
?>
</select>

If I enter a wrong value in one of the post inputs that has a validation rule in Post model, it redirects to the current add view, shows what is the validation error, but then the $locations array passed from controller to view disappears and can't use it in view and I get this error:

Notice (8): Undefined variable: locations [APP\View\Posts\add.ctp, line 68]

© Stack Overflow or respective owner

Related posts about php

Related posts about cakephp