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 !!
Related
I want to display a form multiple times by clicking a button in vuejs, how is it possible?
is it possible to read number in a column from the database and display a form based on that number, for example if i want to register garage and also number of cars in that garage, by reading the number of cars in the garage table , i want to display number of forms based on that cars.
if it is two cars in the garage, then two forms will be displayed and so on.
There are tons of ways to do it, and the representation is delivered via v-for.
Specifics depend on what you want to show in form, are there loaded values, how do you want to save them etc.
In this example i get some variable form backend (it can also just be 0, as is the default value), and add a form item object for the received amount or whenever you press the button to the array that is iterated through. If you use Vue.set or =, Vue will notice difference and rerender the component with the changed v-for loop. (it doesn't notice, for example, push)
Then you would just submit and/or validate formValues
Alternatively you could also do something similar to v-for="number in range(0, 4)" and track the form values somehow else. Either way, world is your oyster.
<template>
<div>
<div v-for="(form, index) in formValues" v-key="index">
<form>
<input v-model="formValues[index].yourFormVariable">
<input v-model="formValues[index].yourOtherFormVariable">
</form>
<div>
<button #click="addCar()">
</div>
</template>
<script>
...
data () {
return {
formValues: [],
carAmount : 0,
}
},
...
methods () {
getCarAmount () {
/*however you want to get your variable from wherever, should launch it on computed or whenever you want to reset the value*/
this.carAmount = response.data.carAmount // carAmount being the db variable
for(let i = 0; i < this.carAmount; i++){
this.addCar()
}
},
addCar () {
this.formValues[this.carAmount] =
{
yourFormVariable: '',
yourOtherFormVariable: '',
};
this.carAmount++;
}
},
</script>
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!
I have been trying to figure out this problem I've been having all day. I will give you a simplified run down of what I have been trying to do. The user enters a number, and however much the number is, is the number of categories there are going to be on the following page. Within each category, there is an input text button, along with an "Add Textbox" button that adds additional input textboxes dynamically. However, the problem here is that each category has this same setup on the same page. For example, if the user enters the number "3", then the page will vertically load three categories looking something like the following:
Category #1
(Initial user input textbox for category #1)
("Add Textbox" button to allow user to fill out another option)
Category #2
(Initial user input textbox for category #2)
("Add Textbox" button to allow user to fill out another option)
Category #3
(Initial user input textbox for category #3)
("Add Textbox" button to allow user to fill out another option)
The struggle I have been encountering is that each category button will need to have its own function, to tell the button where to place the textbox. This coupled with the fact that the number of categories changes depending on the user's input, has made things difficult. I started with the following:
var categoryCount = <?php echo $categoryCount; ?>;
var click = {};
for (var num=1;num<=categoryCount;num++) {
var newClick = "click_" + num;
click[newClick] = function() {
// some contents when this button is clicked
};
}
This JS creates an object of functions, which in JS would be able to be accessed by doing something like the following:
click['click_' + someID]();
However, the problem is that I cannot do this using the "onclick" attribute in my HTML/PHP button. I cannot access this object of functions, and cannot call any of the individual functions, obviously. I think I am going to need to rethink all of this and start again. I just can't think of another way to get this to work. Please share your ideas with me! Your help would be greatly appreciated.
For something like this, I'd write a constructor I could use like this
var cat1 = new Category(document.body);
Luckily for you, I also wrote one as an example. See the DEMO HERE. I haven't styled it at all for the new lines etc, though.
var Category = (function () {
var categoryCount = 0;
function elem(tag) { // shortcut
return document.createElement(tag);
}
function text(str) { // shortcut
return document.createTextNode(str);
}
function Category(node) {
var self = this; // this should have been var'd, oops!!
this.categoryId = ++categoryCount;
// make add button
this.addButton = elem('button');
this.addButton.appendChild(text('Add Textbox'));
this.addButton.addEventListener('click', function () {
self.addTextbox();
});
// make wrapper
this.wrapper = elem('section');
this.wrapper.setAttribute('id', 'cat'+this.categoryId);
this.wrapper.appendChild(this.addButton);
// make textboxes
this.textboxes = [];
this.addTextbox();
// append to document
if (node) {
this.append(node);
}
}
Category.prototype.addTextbox = function () {
var e = elem('textarea');
e.setAttribute('name', 'cat-'+this.categoryId+'-textbox[]');
this.textboxes.push(e);
this.wrapper.insertBefore(e, this.addButton);
};
Category.prototype.append = function (node) {
return node.appendChild(this.wrapper);
};
return Category;
}());
I am programming in php,
I want to take an array I have (which is extracted from mysql result set), convert it to JSON and then use it in dojox.grid.DataGrid.
I got an idea from this link:
I used the following on the array (in a file called getJSON.php)
echo $ajax = "{identifier: 'db_id', 'items':".json_encode($array)."}";
Then I try doing this (in my main page):
var store = new dojo.data.ItemFileWriteStore({ url: 'getJSON.php' });
Everything else is exactly as the Dojo documentation specifies.
The grid shows up, but doesn't load the data and instead writes Sorry, an error occurred
Does anyone know the reason? Hopefully I gave you enough to go on.
i don't use ItemFileWriteStore for that ! They changed a lot since Dojo 1.6 , so maybe you looked at something not up to date.
Try this code:
// Load the neccessary components (This is dojo with AMD ) !
require(["dojo/aspect",'dojo/_base/lang', 'dojox/grid/DataGrid'
,'dojo/dom' , 'dojo/store/JsonRest','dojo/data/ObjectStore',
'dojo/domReady!'],
function(aspect,lang, DataGrid, dom,JsonRest,ObjectStore){ // Map components to vars...
var store = new JsonRest({
target: "getJSON.php" // Use a URL that you can open up in a browser.
});
/*layout for the grid, you will have to adapt this to your columns !!!*/
var layout = [[
{'name': 'Filename', 'field': 'documentName', 'width': '300px'},
{'name': 'Size', 'field': 'fileSize', 'width': '100px'},
{'name': 'Id', 'field': 'id', 'width': '200px'}
]];
dataStore=ObjectStore({objectStore: store}); // Transform to Objectstore !
/*Now we create a new grid*/
var grid = new DataGrid({
id: 'grid',
store:dataStore, // Connect the store
autoWidth:false,
structure: layout, // Connect the layout
rowSelector: '0px'});
grid.placeAt("yourTargetDivId"); // Has to be an existing DOM Element with id !
grid.startup(); // START IT !
});
Please try this code by echoing something simple like this first:
echo '[{"id":"1","fileSize":"100kb","documentName":"Lucian !"},
{"id":"2","fileSize":"900kb","documentName":"Pew Pew !"}]';
And after that with your own JSON...
I am new to jquery and jqgrid, but i am comfortable with javascript. However I have managed to install jqgrid after some effort.
I have been trying a to find a solution to enable ore disable the delete feature from the navigation bar based on the value of the 'lock' column. I read the following link
jqgrid: how to set toolbar options based on column value in row selected
But I was not able to get the contents of 'lock' cell for the javascript. I also tried to format the lock string without effect.
the jqgrid is loaded via php. The script is here http://www.trirand.net/demophp.aspx
The php script is the following
require_once("JQGrid/jq-config.php");
require_once("JQGrid/php/jqGridASCII.php");
require_once("JQGrid/php/jqGridPdo.php");
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
$grid = new jqGridRender($conn);
$grid->SelectCommand = 'SELECT * FROM `device_assignement` ';
$grid->dataType = 'json';
$grid->setColModel();
$grid->setUrl('Grid_ecu_display.php');
$grid->setColProperty("company",
array("label"=>"Dealer Name",
"width"=>350
),
array( "searchrules"=>
array("searchhidden"=>false, "required"=>false, "search"=>false)));
$grid->setGridOptions(array(
"sortable"=>true,
"rownumbers"=>true,
"rowNum"=>40,
"rowList"=>array(10,50,100),
"sortname"=>"ecu",
"width"=>940,
"height"=>400,
"shrinkToFit"=>true,
"hidden" => true,
"hoverrows"=>true ));
$grid->toolbarfilter = true;
$grid->setFilterOptions(array("stringResult"=>true));
$grid->setColProperty("ecu", array(
"label"=>"ECU Number" ,
"sortable"=>true
));
$grid->setColProperty("lock", array(
"label"=>"<i>Lock</i>" ,
"width"=>60,
"sortable"=>false,
"editable"=>true
));
etc etc...
$ecu = jqGridUtils::GetParam('ecu');
// This command is executed immediatley after edit occur.
$grid->setAfterCrudAction('edit', "UPDATE `ecu_master` SET `lock` = '1' WHERE `ecu` =?",array($ecu));
$grid->navigator = true;
$grid->setNavOptions('navigator', array("pdf"=>true, "add"=>false,"edit"=>true,"del"=>false,"view"=>false, "excel"=>true));
$grid->setColProperty('company',array("searchoptions"=>array("sopt"=>array("cn"))));
$oper = jqGridUtils::GetParam("oper");
if($oper == "pdf") {
$grid->setPdfOptions(array(
// set the page orientation to landscape
"page_orientation"=>"L",
// enable header information
"header"=>true,
// set bigger top margin
"margin_top"=>27,
// set logo image
//"header_logo"=>"logo.gif",
// set logo image width
//"header_logo_width"=>30,
//header title
"header_title"=>"Autograde CMS ECU Allocation List",
// and a header string to print
"header_string"=>"$SoftwareVersion"
));
}
// Run the script
$grid->renderGrid('#grid','#pager',true, null, null, true,true);
This is included in another php script where.
All I want is to enable or disable the delete row button based on the "lock" value
If this seems too basic and ridiculous please let me know I will understand.
If the user click on a cell of the grid the whole row will be selected and the callback function onSelectRow will be called. So you should implement the callback function onSelectRow which has the rowid (the id of the <tr>) as the first parameter. Inside of the onSelectRow handler you can call getCell method. Depend on the value of the 'lock' column (which can be hidden if needed) you can enable of disable "Edit" and "Delete" buttons of the navigator bar.
So the code can be about the following:
$('#list').jqGrid({
... all other jqGrid options which you need
pager: '#pager',
onSelectRow: function (rowid) {
var gridId = $.jgrid.jqID(this.id);
// test 'lock' column for some value like 'yes'
if ($(this).jqGrid('getCell', rowid, 'lock') === 'yes') {
// disable the "Edit" and "Delete" buttons of the navigator
$("#edit_" + gridId).addClass('ui-state-disabled');
$("#del_" + gridId).addClass('ui-state-disabled');
} else {
// enable the "Edit" and "Delete" buttons of the navigator
$("#edit_" + gridId).removeClass('ui-state-disabled');
$("#del_" + gridId).removeClass('ui-state-disabled');
}
}
}).jqGrid('navGrid', '#pager');
Because you are new in jqGrid I want comment the usage of $.jgrid.jqID() function. In the most cases if returns the value of the input parameter: 'list' in case of the example. It's needed for more common case if the id of the grid (the id of the <table> element) contains meta-characters. $.jgrid.jqID() function include additional escape characters (two backslashes: \\) before any meta-character.