Cakephp表单输入自动完成
我正在使用CakePhp 2.2.1并且我在实现我刚才在标题中提出的问题时遇到了一些问题,我找到了几个教程但是大多数都是针对cakephp 1.3而其他都不是我想做的。 我有一个“events”表,其中包含一个“player_id”,因此一个Player有很多事件,一个事件属于一个Player。
在我的活动添加表单中,我按照食谱说明,我得到一个可供选择的玩家下拉列表,但我想要的只是写出玩家的名字并从自动完成结果中选择我想要的那个。 这些球员也必须来自我之前选择的球队。 有任何想法吗?
提前致谢。
特别感谢Andrew指出这个api.jqueryui.com/autocomplete 。 但是没有真正的指南来使用这个。 所以我找到了这篇文章 ,它解释了Abhishek的第二个链接所说的但我能更好地理解它。 如果有人有兴趣,这是我的解决方案:
1 – 从自动填充页面下载您需要的.js。 将其保存在app / webroot / js中
2 – 在您的app / View / Layouts / default.ctp中或在视图中您要使用自动完成添加:
echo $this->Html->script('jquery-1.9.1.js'); echo $this->Html->script('jquery-ui-1.10.3.custom.js'); echo $this->fetch('script');
3 – 在您的视图中添加(我的是add_goal.ctp):
4 – 在你的Controller中(mina是EventController.php):
public function autoComplete($team = null){ Configure::write('debug', 0); $this->autoRender=false; $this->layout = 'ajax'; $query = $_GET['term']; $players = $this->Event->Player->find('all', array( 'conditions' => array('Player.team_id' => $team, 'Player.name LIKE' => '%' . $query . '%'), 'fields' => array('name', 'id'))); $i=0; foreach($players as $player){ $response[$i]['id']=$player['Player']['id']; $response[$i]['label']=$player['Player']['name']; $response[$i]['value']=$player['Player']['name']; $i++; } echo json_encode($response); }
访问下面的链接,这可能会帮助你,因为ajax助手不再是在cake2.X版本核心所有相关的function移动到JS帮助类。(这里为用户贡献的AJAX助手的第三个链接可能会帮助你)
http://bakery.cakephp.org/articles/matt_1/2011/08/07/yet_another_jquery_autocomplete_helper_2
要么
http://nuts-and-bolts-of-cakephp.com/2013/08/27/cakephp-and-jquery-auto-complete-revisited/
要么
http://bakery.cakephp.org/articles/jozek000/2011/11/23/ajax_helper_with_jquery_for_cakephp_2_x
您需要使用ajax,因为您的自动填充结果取决于您选择的团队。 在jquery中有这样的东西:
var team = $('#teamdropdown').find(":selected").text(); $.ajax({ type: "POST", url: 'http://domain.com/playersdata', data: {'team':team}, success: function(data){ console.log(data); //put data in for example in li list for autocomplete or in an array for the autocomplete plugin }, });
在playerdata页面(控制器或模型)的蛋糕上这样的东西。
if( $this->request->is('ajax') ) { $arr_players = $this->Players->find('all', array('conditions'=>array('team'=>$this->request->data('team')))); //pr($this->request->data) to get all the ajax response echo json_encode($arr_players); }
还要将标头设置为json respons和$ this-> layout = null; 删除布局tpl。
另一种解决方案是在你的php中使用json_encode并将其传递给js-code之类的
这个解决方案只对少量数据感兴趣,如果你有一个包含团队和玩家的大型数据库,我不推荐这个,因为如果你只需要一点点就加载所有这些数据…我没有’ t测试代码,但它应该帮助你继续…
祝好运!