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]
Most likely this is caused by where you set the
$locationsvariable with$this->set(), and this is only happening in case of a GET request.When submitting the form, you are sending a POST/PUT request instead of a GET and the code inside
ifclause is never executed – therefore$locationsvariable is available in your View file.If you only want to load those values when displaying a clean form, you might change the
ifcondition to check if$this->request->dataarray is populated with user’s submitted values.