我正在开发一个 CakePHP 项目,我有用户、帖子和位置模型等。User hasMany Location 和 Post belongsTo User 所以 Location 与 Post 没有直接关系。
这是我在 Post 控制器中的代码:
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')))));
}
...
}
这是我在帖子/添加视图中的代码:
<?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>
如果我在 Post 模型中具有验证规则的 post 输入之一中输入了错误的值,它会重定向到当前的添加视图,显示验证错误是什么,但是从控制器传递到视图的 $locations 数组会消失并且可以'不要在视图中使用它,我得到这个错误:
Notice (8): Undefined variable: locations [APP\View\Posts\add.ctp, line 68]