Cakephp form input with autocomplete - php

I am using CakePhp 2.2.1 and I am having some problems to implement what I just asked in the title, I found several tutorials but most of them are for cakephp 1.3 and the others are not what I want to do. I have a "events" table which contains a "player_id" thus a Player has many Events and an Event belongs to a Player.
In my Event add form I proceed as the cookbook says and I get a dropdown list of players to choose from, however what I want is to just write the names of the players and select the one I want from the autocomplete results. Also these players must be from the team that I select before that. Any ideas?
Thanks in advance.

Special thanks to Andrew for pointing out this api.jqueryui.com/autocomplete. However there is not a real guide to use this one. So i found this post, which explains what Abhishek's second link says but I could understand it better. So here is my solution if anyone is interested:
1 - Download from the autocomplete page the .js you need. Save it in app/webroot/js
2 - Either in your app/View/Layouts/default.ctp or in the view you want to use the autocomplete add:
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 - In your view add (mine was add_goal.ctp):
<script>
$(document).ready(function(){
var myselect = document.getElementById("EventTeam"); //I needed to know which team I was looking players from.
var team = myselect.options[myselect.selectedIndex].value; //"EventTeam" was a dropdown list so I had to get the selected value this way.
$("#EventPlayer").autocomplete({
source: "/events/autoComplete/" + team,
minLength: 2, //This is the min ammount of chars before autocomplete kicks in
autoFocus: true
});
$("input:submit").button();
$("#EventPlayerId").autocomplete({
select: function(event, ui) {
selected_id = ui.item.id;
$('#EventAddGoalForm').append('<input id="EventPlayerId" type="hidden" name="data[Event][player_id]" value="' + selected_id + '" />');
}
});
$("#EventPlayerId").autocomplete({
open: function(event, ui) {
$('#EventPlayerId').remove();
}
});
});
</script>
4 - In your Controller (mina was 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);
}

visit below link ,this might help you as the ajax helper is no more in cake2.X versions core all related functionality moved to JS helper class.(here third one link for AJAX helper for contributed by user may help you)
http://bakery.cakephp.org/articles/matt_1/2011/08/07/yet_another_jquery_autocomplete_helper_2
or
http://nuts-and-bolts-of-cakephp.com/2013/08/27/cakephp-and-jquery-auto-complete-revisited/
or
http://bakery.cakephp.org/articles/jozek000/2011/11/23/ajax_helper_with_jquery_for_cakephp_2_x

You need to use ajax because your autocomplete-results depends on the team you have selected.
Something like this in 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
},
});
And in cake on playersdata page (Controller or model) something like this.
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);
}
Also set headers to a json respons and $this->layout = null; to remove the layout tpl.
Another solution would be to use json_encode in your php and pass it to js-code like
<script>var players = <?php echo json_encode($array_players_with_teams); ?>; </script>
This solution is only interesting for a small amount of data, if you have a big database with teams and players I wouldn't recommend this, because why load all this data if you only need just a bit of it...
I didn't test the code but it should help you to go on...
Good luck!

Related

laravel working with city and area select

I was wondering if there is an easy way to work with multiple select boxes in Laravel. I am trying to make a city box, if the city is selected, if want to load the next controller that shows the areas in the city. Would this even be possible for a form?
Thank you
Thank you, guys.
It was quite easy to make.
Never expected it to be this easy.
I did it by setting a route to a new controller and working with javascript.
To the people that would like to make this in the near future.
Below you can find an idea of code that I have used for Laravel;
Javascript
$(document).ready(function () {
$('#city').change(function () {
var city = $("#city option:selected").val();
$.ajax({
url: "https://anma-maching-dev.aska-ltd.jp/destinations",
data: {
"city" : city
},
success: function(result){
jQuery('.area').html('');
$( ".area" ).fadeIn("fast", function() {
$(".area").append(result);
});
}
});
});
});
I attached the output of the controller to a div class called area!
route
Route::get('/destinations', 'destinationsController#get_area');
strong text
public static function get_area()
{
// your query to select the next information for your textBox
}

How to preload <options> and <select> with Jquery-option-tree plugin

I am using Jquery-option-tree plugin on a standalone website not based on Wordpress as in example 7 on the demo page, except that I am not passing a .txt file but a PHP page is generating the array of < options > to be passed to the plugin.
http://kotowicz.net/jquery-option-tree/demo/demo.html
This perfectly works: so let's say that the user wants to select a category for a new product, the plugin suits the purpose generating a nice: " Food -> fruit -> apples " upon user clicks. (see demo page ex. 7)
What instead if a product already exists with its categories assigned? I want to show it to the user when he edit that product, preloading the tree.
I have the ids path coming from database, so it would just be a matter of having the plugin to run without the user interact, using the value I pass. I saw this question: jQuery simulate click event on select option
and tried to simulate user' click with this (and other) methods with no luck.
$('#select')
.val(value)
.trigger('click');
Here the call to the function:
$(function() {
var options = {
empty_value: '',
set_value_on: 'each',
indexed: true, // the data in tree is indexed by values (ids), not by labels
on_each_change: '/js/jquery-option-tree/get-subtree.php', // this file will be called with 'id' parameter, JSON data must be returned
choose: function(level) {
return 'Choose level ' + level;
},
loading_image: '/js/jquery-option-tree/ajax-load.gif',
show_multiple: 10, // if true - will set the size to show all options
choose: ''
};
$.getJSON('/js/jquery-option-tree/get-subtree.php', function(tree) { // initialize the tree by loading the file first
$('input[name=parent_category_id]').optionTree(tree, options);
});
});
Here you can see the plugin:
https://code.google.com/p/jquery-option-tree/
I don't know that plugin, but looking at the examples there seems to be one that fits your need; Example 6 - AJAX lazy loading & setting value on each level change.
This would, in theory, just require some config options:
preselect: {'demo6': ['220','226']}, // array of default values - if on any level option value will be in this list, it will be selected
preselect_only_once: true, // prevent auto selecting whole branch when user maniputales one of branch levels
get_parent_value_if_empty: true,
attr: "id" // we'll use input id instead of name
If this doesn't fit you need though, you could initiate it from an event, like change, keyup, etc.
$(document).on('change', '#select', function() {
$('#nextSelect').val($(this).val());
})
$(document).on('change', '#nextSelect', function() {
$('#finalInput').val($(this).val());
})
Yes, you are right Mackan ! I saw that "preselect" option but I was initially unable to use it transferring the path from database to javascript, I ended up with my "newbie" solution to match the syntax:
preselect: {'parent_category_id': [0,'2','22']},
PHP
$category_path comes from DB query and is like "0,2,76,140,"
$path = explode(',', $category_path);
$preselect="";
foreach ($path as $value) {
$int = (int)$value;
if ($int != 0) $preselect.= "'". $int ."',";
else $preselect.= $int.","; // have to do this as ZERO in my case has to be without apostrophes ''
}
$preselect = "{'parent_category_id':[".$preselect."]}"
JS
var presel= <?php echo($preselect); ?>;
var options = {
preselect: (presel),
}
Any suggestion for a better code ?
Thanks a lot !!

Suggestions on the search filter

I am working on a website in the codeigniter framework. I am stuck at a point where I need to implement the auto complete feature. I have tried a lot but I am not able to find proper solution so far. Here is what my actual requirements are.
There is a page on website that has few search filters. When a person lands on this page all the users of the website are shown on that page. Here the real game starts. There is a filter or an input box that filters out the results on the basis of their first or last name.
Say I have a database in which i have 3 users.
Ahmad Nawaz
John Azaar
Monica Finlay
When a person starts typing "Ah" in that search box I want that the sugesstions start to appear showing him "Ahmad"... Please tell me how to do that? I have searched a lot out there but i could not find a proper answer in reference to codeignitor. this is what my code looks like at the moment...
<input type="text" placeholder="Persons Name" name="individual_name" id="individual_name">
<script>
$(function() {
$( "#individual_name" ).autocomplete({
source: ('autocomplete_individual_name'),
select: function () {
testing()
}
});
});
</script>
just under the input I wrote the script....It goes to my mentioned controller. Here is what the controller looks like...
$individual_name = $this->input->post('individual_name');
$where = "first_name LIKE '".$individual_name."%' OR last_name LIKE '".$individual_name."%'";
$users_array = $this->user_profile_model->findByCondition($where);
First Problem
$individual_name is not getting populated.
Second Problem
When I receive the results in users_array, what should I do next? How to pass it back to show suggestions??
Third Problem
I use to call a filter function onkeyup(). Now when a person selects through the suggestion how to call the filter?
P.S->Also kindly let me know how can i reply to the person who replies me on this question...I have used # sign with user but it seems they dont get my reply thats why they never returned....
Any help would be highly highly appreciable...
Thanks and waiting
Ahmad
Try something like this, You may need to change the code slightly to suit you,
In your script part:
$("#individual_name").autocomplete({
source : base_url+"controller_name/suggest_names",
minLength : 1,
select: function( event, ui ) {
alert('id :'+ui.item.value) ;
//document.location.href = base_url+"controller_name/search?keyword="+ui.item.value; do something or redirect
},
success : function(resp){
//alert("auto");
},
error : function(){
alert("Oops, that didn't work. Please try again.");
}
});
In your controller:
function suggest_names(){
print_r ( $this->model_name->suggest_names($_REQUEST['term']) );
}
In your model part:
function suggest_names($term){
$data = array();
$term = strtolower( addslashes( trim( urldecode($term) ) ) );
$temp = $this->db->select('name as label, id as value')->like('name', $term, 'LEFT')->get('table_name')->result_array();
$data = json_encode($temp);
//echo "<pre>";print_r($data);echo "</pre>";die;
return $data;
}
Let me know if you face any problem. Hope it works for you.

JQuery PHP AJAX filter based on multiple checkbox array

I'm hoping someone can point me in the right direction. I'm primarily a PHP developer but I'm really trying to get my head around jquery and javascript more due to the increasing number of AJAX work requests we receive.
Basically I have a sidebar filter that works fine. It is based on 3 things. A group, category and sub category. So for example, Boots as the category, Leather (type) as a sub category and Black (colour) as tertiary filter. At the moment it works based on a GET form. However I want to use live filters instead so as they click a checkbox, it updates the results based on a query. I can write all the PHP for this but I'm struggling to get the data together by jQuery. I've looked at using jQuery .each and .change.
There are 3 groups of checkboxes and they are all based on arrays. So for example again: category[], subcategory[], tertiary[].
Thanks in advance for the help.
Some example HTML
<input id="$ProdCatLabel" class="side_filter_checkbox" name="ProdCatFil[]" type="checkbox" value="$ProdCat">
<input id="$ProdSubCatLabel" class="side_filter_checkbox" name="ProdSubCatFil[]" type="checkbox" value="$ProdSubCat">
<input id="$BrandingLabel" class="side_filter_checkbox" name="BrandFil[]" type="checkbox" value="$Branding">
My attempts:
var prodcats = $('side_filter_prodcats[name="ProdCatFil[]"]:checked')
.map(function() { return $(this).val() })
.get()
.join(",");
var prodsubcats = $('side_filter_prodsubcats[name="ProdSubCatFil[]"]:checked')
.map(function() { return $(this).val() })
.get()
.join(",");
$.ajax({
type: "POST",
url: "[ENTER PHP URL HERE]",
data: "ProdCats=" + prodcats + "ProdSubCats=" + prodsubcats,
success: function(msg) { $(".content_area").html(msg); }
});
Am I barking up the right tree here?
Ok let's say your checkboxes have the classes category, subcategory and tertiary. You could attach a click event handler to each group that calls the function to load in the correct data, passing the checkbox value and a class or data-attribute to the function as parameters.
// Your main DOM ready function
$(document).ready(function() {
// Checkboxes click function
$('input[type="checkbox"]').on('click',function(){
// Here we check which boxes in the same group have been selected
// Get the current group from the class
var group = $(this).attr("class");
var checked = [];
// Loop through the checked checkboxes in the same group
// and add their values to an array
$('input[type="checkbox"].' + group + ':checked').each(function(){
checked.push($(this).val());
});
refreshData(checked, group);
});
function refreshData($values, $group){
// Your $values variable is the array of checkbox values
// ie. "boot", "shoe" etc
// Your $group variable is the checkbox group
// ie. "category" or "subcategory" etc.
// Now we can perform an ajax call to post these variable to your php
// script and display the returned data
$.post("/path/to/data.php", { cats: $values, type: $group }, function(data){
// Maybe output the returned data to a div
$('div#result').html(data);
});
}
});
Here's an example of the checkbox click function in action: http://jsfiddle.net/F29Mv/1/

jQuery Connected Sortable Lists, Save Order to MySQL

Hoping that using something like this demo it is possible to drag items within and between two columns, and update their order either live or with a "save" button to MySQL. Point being that you can make changes and return to the page later to view or update your ordering.
http://pilotmade.com/examples/draggable/
Doing it for just one column is fine, but when I try to pass the order of both columns, the issue seems to be passing multiple serialized arrays with jQuery to a PHP/MySQL update script.
Any insight would be much appreciated.
If you look below, I want to pass say...
sortable1entry_1 => 0entry_5 => 1
sortable2entry_3 => 0entry_2 => 1entry_4 => 2
EDIT: This ended up doing the trick
HTML
<ol id="sortable1"><li id="entry_####">blah</li></ol>
jQuery
<script type="text/javascript">
$(function()
{
$("#sortable1, #sortable2").sortable(
{
connectWith: '.connectedSortable',
update : function ()
{
$.ajax(
{
type: "POST",
url: "phpscript",
data:
{
sort1:$("#sortable1").sortable('serialize'),
sort2:$("#sortable2").sortable('serialize')
},
success: function(html)
{
$('.success').fadeIn(500);
$('.success').fadeOut(500);
}
});
}
}).disableSelection();
});
This is the PHP query
parse_str($_REQUEST['sort1'], $sort1);
foreach($sort1['entry'] as $key=>$value)
{
do stuff
}
what I would do is split them up
data :
{
sort1:$('#sortable1').sortable('serialize'),
sort2:$('#sortable2').sortable('serialize')
}
then when you post you can get the request and set them as needed, I hope that makes sense
so what I do is this
parse_str($_REQUEST['sort1'],$sort1);
foreach($sort1 as $key=>$value){
//do sutff;
}

Categories