I'm working on a Extjs 4 application and I'm at a point where I need to create view components dynamically.
I have a store that's loaded with new items when I select a value from a combobox. And I want to create a new view component for each item the new store has.
I'm using Extjs 4 with the MVC architecture.
This is the function that creates a new combobox that's fired when I choose an Item from another combo :
function createComboBox(label) {
var combo = new Ext.form.ComboBox({
displayField: 'combo',
typeAhead: true,
mode: 'local',
forceSelection: true,
triggerAction: 'all',
emptyText: 'Select item...',
selectOnFocus: true,
fieldLabel: label
});
return combo;
}
This is the code inside my "select combobox" handler event :
onSelectedValue: function (combo) {
var selected = combo.getValue();
var guiDataStore = this.getGuiDataStore();
guiDataStore.getProxy().url = 'gui_comp_items.php?id_metric=' + selected;
guiDataStore.load({
params: {
id_metric: selected
},
scope: this,
callback: function () {
var paramsRef = this.getParams();//this is the view where I'd like to create the combobox
var total = guiDataStore.getTotalCount();
if (total > 0) {
guiDataStore.each(function (model) {
if (model.get('type_guicomp') == 'combobox') {
paramsRef.down('fieldset[id=filterfieldset]').add(createComboBox(model.get('name_filter')));
paramsRef.down('fieldset[id=filterfieldset]').doLayout();
}
})
}
}
})
}
So my problem is, the first time I choose an item from the existing combobox and total = 0 , no combobox is created and everything is fine, then when I choose a value that returns total = 2, 2 new comboboxes are created, that's perfect. BUT, when right after that, I choose again a value with total = 0, the store is not updated and I STILL get 2 new comboboxes.
Is there a problem with my callback? Please any help would be much appreciated.
Once guiDataStore has 2 records in it, why would it be empty next time?
As in, do you empty the store between the various callback calls?
Related
It's more of a logical question than code...
So I have 2 tables in the DB: kpiInvoices and kpiTerms
The kpiInvoices table is where the user's entered data will be saved to and displayed in a DataTable.
When the user creates a new KPI invoice it will show the form above. I want the SLA Term to be <select> and fetches the data from the kpiTerms Table. When the user selects a term, the Cost input automatically fetches and show the cost of that selected term. Then submits the form and saves the data in kpiInvoices table.
Do I need to create relationships for the 2 tables?
Should I use Eloquent Relationships?
Should I use App\Models\KPITerms in the KPIInvoiceController and do a foreach loop in the blade?
So I made an ajax request to both SLATerm and SLACost and looped through the requested data. Then I made an if statement within the loop to change the SLACost based on the SLATerm selected.
function fetchSLA() {
$.ajax({
type: 'GET',
url: "/management/kpi/fetch/sla",
dataType: 'json',
success: function (response) {
$.each(response.SLATermData, function (key, value) {
$("select[name='SLATerm']").change(function() {
if ( $("select[name='SLATerm']").val() == value.SLATerm ) {
$("input[name='SLACost']").val(value.SLACost);
}
});
});
}
});
}
And here is the Laravel controller for the API:
/**
** KPI API
**/
public function fetchSLA()
{
$kpiTerms = KPITerms::get(['SLATerm' => 'SLATerm', 'SLACost' => 'SLACost']);
return response()->json([
'SLATermData' => $kpiTerms, // SLATermData is the name that will be used in Ajax.
]);
}
I'm a noobie of PHP and AngularJS.
I have a webpage that communicates to a web serves with PHP - AJAX. It queries a database, and echoes the result (a big table) in an html placeholder.
I want to print the content of that table in a downloadable PDF file when the user pushes a button.
I want to use PDFmake and now it works well for test purpose, but how can I pass that content of my table to AngularJS' app?
Maybe should I pass table's id to docDefinition content? In that case I don't know how to do that.
Note: Maybe my approach is uncorrent cause I have to relegate PHP to different tasks and use AngularJS to query the Database, but for now I want to mantain this approach.
Thank You
I suggest you use an angular service (as explained in the docs
)
var bigTableApp = angular.module('bigTable',[])
bigTableApp.factory('BigTableSrv', ['$resource',
function($resource) {
return $resource('URL_to_php_backend', {}, {
query: {
method: 'GET',
params: {param1: 'value 1', param2: 'value 2'},
isArray: true
}
});
}
]);
Then, you can use it in a controller to fetch data from the back-end and build a table structure in PDFmake's table format:
bigTableApp.controller('BigTableController', ['$scope', 'BigTableSrv',
function BigTableController($scope, BigTableSrv) {
$scope.bigTable = BigTableSrv.query();
$scope.pdfMakeTable = {
// array of column widths, expand as needed
widths: [10, *, 130],
body: []
};
$scope.printTable = function() {
pdfMakeTable.body = $scope.bigTable.map(el => {
// process each element of your "big table" to one line of the
// pdfMake table, size of return array must match that of the widths array
return [el.prop1, el.prop2, el.prop3]
});
// create the pdfMake document
let docDefinition = {
content: [ pdfMakeTable ]
}
// print your pdf
pdfMake.creatPdf(docDefinition).print()
}
}
]);
I am working on a website written in Yii framework (version 1.1.14) that allows uploading and displaying news. The admin of the site can select three news to promote to homepage and specify the order in which they are displayed. I am using Mysql database. The news table has two fields: isChecked (0 or 1) and homepagePos (integer) in addition to the other fields. The isChecked field determines whether the news is selected for displaying in homepage and the homepagePos field determines the order in which the news are displayed. I have used jquery's sortable plugin to sort the news. When the user selects which news to display and clicks save button, the news ids are sent to php via ajax.
The javascript portion to send the values to news controller is as follows:
$(document).on('click', '#saveToHomepage', function()
{
var url = ajaxRequestSendUrl; //ajaxRequestSendUrl contains url to news controller's promote to homepage method.
$.ajax({
method: "GET",
url: url,
data: {
contentIds: contentIds, //contentIds contains an array of news Ids in certain order
},
success: function() {
// Show success message
},
error: function() {
alert('Some error occured. Please reload the page and try again.');
}
});
});
Here's the promote to homepage method in news controller:
public function actionHomepage()
{
$allNews = News::model()->findAll();
$value = $_GET['contentIds'];
foreach ($allNews as $news) {
if($news->id == $value[0] ||$news->id == $value[1] ||$news->id == $value[2])
{
$news->isChecked = 1;
$news->homepagePos = array_search($news->id, $value); //Assign index of the array as the position
$news->save();
}
else
{
$news->isChecked = 0;
$news->homepagePos = -1;
$news->save();
}
}
}
My problem is that the news table I have has over 2k data. So the ajax call takes really long time (over a minute) to complete. Is there any way I can optimize the code or is there other way I can approach this to reduce the time taken to complete this operation?
Thanks in advance
Three queries: One first to set the whole table to not checked status, and the rest to set the checked status only in the row each selected id
public function actionHomepage()
{
$values = $_GET['contentIds'];
$sql = "UPDATE news SET idChecked=0,homepagePos = -1";
Yii::app()->db
->createCommand($sql)
->execute();
for($ii = 0; $ii < 3; $ii++) {
$sql = "UPDATE news SET idChecked = 1,homepagePos = ':homepagePos' WHERE id=:id";
Yii::app()->db
->createCommand($sql)
->bindValues(array(':homepagePos' => array_search($ii, $values), ':id' => $values[$ii]))
->execute();
}
}
i am not sure, but why don't you get the filtered records from the database itself by sending the id's of selected news. I don't know your backend language. Seems, you are getting all the records and applying filtering. which consumes time. Instead get the filtered news from the database.
Hope this helps!
Its taking a long time because you're fetching all the records and then updating those three id. You could try this:
$criteria = new CDbCriteria;
$criteria->addInCondition( "id" , $value ) ; // $value = array ( 1, 2, 3 );
News::model()->updateAll(array('isChecked'=>'1','homepagePos'=>'val2'), $criteria);
You could do an update before hand to reset all the homepagePos and then update only the ids you need.
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 !!
I have a multiselect drop down, on selecting multiple items from it, i need to pass the value of this multiselect into an ajax file, and create divisions dynamically and load the data retreived from the ajax files into these dynamic divisions.
var itemvalues= [];
$('#MultiSelectItemID :selected').each(function(i, selected) {
itemvalues[i] = $(selected).val();
});
$('#itemContent').html(LoadHTML);
$('#itemDetailsContainer').fadeIn('',function(){
$('#itemContent').load('ajax_calls/item_details.php?ItemID='+$('select[name=MultiSelectItemID]').val() || [],
function(){
$(this).show('highlight');
}); });
Now , i want to loop through each value in the itemvalues[] array and pass it to my php file and get the data and load it into a new division.
Please help.
Will this do the job? (Note I 've changed "MultiSelectItemID" to simply "ItemID" and serialize()d it.)
http://jsfiddle.net/svzsY/8/
var itemvalues = [];
$('#itemContent').html(LoadHTML);
$('#itemDetailsContainer').fadeIn('', function() {
$('#itemContent').load('ajax_calls/item_details.php', ($('select[name=ItemID]').serialize() || []), function() {
$(this).show('highlight');
});
});