1)I have a json file which I want to display in view.
{
"contents": [
{
"title":'JWorld',
"image":'image/e-learning/elearning.png',
"subtitle":[
{
"categories":'Aus',
},
{
"categories":'England',
}
]
},
{
"title":'JIndia',
"image":'image/Content/History_of_India.jpg',
"subtitle":[
{
"categories":'History',
},
{
"categories":'India palace',
}
]
},
{
"title":'JMaharastra',
"image":'image/Content/Geography.jpg',
"subtitle":[
{
"categories":'History Maharastra',
},
{
"categories":'Maharastra Heros',
}
]
}
]
}
2)My view file :--
Ext.define('Balaee.view.kp.dnycontentcategories.ContentcategoriesView',
{
extend:'Ext.view.View',
id:'contentcategoriesViewId',
alias:'widget.ContentcategoriesView',
store:'kp.DnycontentcategoriesStore',
config:
{
tpl:'<tpl for="0">'+
'<div class="main">'+
'</br>'+
'<b>{title}</b></br>'+
'<img src={image} hight="50" width="100"></br>'+
'</div>'+
'</tpl>',
itemSelector:'div.main',
}
});// End of class
3) i am using tab panel and dynamically adding tabs in it using json file.
Ext.define('Balaee.view.kp.dnycontentcategories.Contentcategories',{
extend:'Ext.tab.Panel',
requires:[
'Balaee.view.kp.dnycontentcategories.ContentcategoriesView','Balaee.view.kp.dnycontentcategories.ContentcategoriesView1'
],
id:'contentcategoriesId',
alias:'widget.Contentcategories',
height:500,
items:[
],//end of items square
});// End of login class
4) My store file:--
Ext.define('Balaee.store.kp.DnycontentcategoriesStore',{
extend: 'Ext.data.Store',
model: 'Balaee.model.kp.DnycontentcategoriesModel',
autoLoad:true,
// filters: [{
// property: 'title',
// }],
proxy:
{
type:'ajax',
api:
{
read:'data/content.json',
//create: ,
//update: ,
//destroy: ,
},//End of api
reader:
{
type:'json',
root:'contents',
//successProperty: ,
}//End of reader
}//End of proxy
});//End
5) My Controller file some code
here I am dynamically adding some tabs from json file.And selecting particular tab I want different particular values from json file. But I get same view of first tab. How can I solve this problem.
init: function(){
console.log("inside content controller");
this.control({
'Contentcategories':
{
render:this.renderFunction,
}
});//End of control
},//End of init() function
renderFunction:function(){
console.log("Inside render function");
var tabPanel = Ext.getCmp('contentcategoriesId'); // tabpanel
var tabPanelView = Ext.getCmp('contentcategoriesViewId'); // tabpanel view
var storeObject= this.getStore('kp.DnycontentcategoriesStore'); // store
storeObject.on('load',function(){
storeObject.each(function(model){
//tabPanelView.store().filter('title',model.get('title')),
console.log(model.get('title'));
console.log(model.get('categories'));
tabPanel.add({title:model.get('title'),
id:model.get('title'),
//html:"<image src=model.get('image')>",
xtype:'ContentcategoriesView',
}); //End of add function
});// End of storeObject function
tabPanel.setActiveTab(0);
});
},// End of render function
please give me some suggestion.
There are a few issues with your code.
You define ContentcategoriesView - its a a component you have extended; but you give it an id (contentcategoriesId) yet you are creating more than one of these components - it makes no sense as an id has to be unique per component instance.
Then, you attach a store to this view, which means all components will render the same.
If I understand correctly you want each entry in your json to become a different tab.
I would take this direction (code not tested, but should give you a direction):
Ext.define('Balaee.view.kp.dnycontentcategories.ContentcategoriesView',
{
extend:'Ext.panel.Panel', // Notice it's a panel.
alias:'widget.ContentcategoriesView',
config:
{
tpl: '<div class="main">' +
'</br>' +
'<b>{title}</b></br>' +
'<img src={image} hight="50" width="100"></br>' +
'</div>'
itemSelector:'div.main',
}
});
And then:
storeObject.on( 'load',function() {
storeObject.each( function( model ) {
tabPanel.add({
xtype: 'ContentcategoriesView',
title: model.get( 'title' ),
id: model.get( 'title' ),
data: model
});
});
tabPanel.setActiveTab(0);
});
Related
I am getting values from the DB to the page where the dropdown box is there but the dropdown box not returning the value. The code as shown below,
Script
methods: {
editState(id){
axios.defaults.headers.common['Authorization'] = "Bearer "+localStorage.getItem('token');
axios.get(baseUrl+'/state/edit/'+id)
.then((response) => {
alert(response.data[0].form.country_name);
this.form = response.data[0].form;
setTimeout(() => {
this.subComponentLoading = true;
}, 500);
})
.catch(function (error) {
console.log(error);
});
}
}
Vue
<d-field-group class="field-group field-row" label-for = "country_name" label="Country Name" label-class="col-4">
<d-select :options="Countries" v-model="form.country_id" id="country_id" name = "country_name" wrapper-class="col-7">
</d-select>
</d-field-group>
Two things that I see are wrong...
Countries is inside the form object but you don't assign or read it from there. Move it to the top level
You are binding a v-model to form.country_id but this does not initially exist. Add it to the form object.
To summarise...
data () {
return {
isStateEditVisible: false,
form: {
state_name: '',
isStateEnabled: true,
ISO_Code: '',
country_id: '', // 👈 added this
country_name: '',
zone_name: ''
},
Countries: [], // 👈 moved this
Zones: [] // 👈 and this
}
}
In order to react to data changes, Vue needs to know about them up-front. See https://v2.vuejs.org/v2/guide/reactivity.html
Trying to do a simple input box. The default value should be a database value, and when user updates the value, it also updates the database. I'm using Laravel 5.5 and this is a vue component. So the initial value would be 3 from the database, but then if someone changes the value, it would also update the database. Am I on the right track with what's below, or am I way off? Currently it won't get the initial amount, and it won't update.
<template>
<div>Corn: <input v-model="corn" style="width: 50px;" /></div>
</template>
<script>
export default {
data: function() {
return {
items: 'not updated',
corn: items.cornquant
} },
watch: { // whenever amount changes, function will run
corn: function(newCorn, oldCorn) {
this.corn = '2'
this.getCorn()
} },
mounted: function() {
this.getVueItems();
},
methods: {
getVueItems: function() {
axios.get('/testing').then(response => {
this.items = response.data;
}); },
getCorn: _.debounce(
function() {
this.corn = 'Thinking...'
var vm = this
axios.put('/corn/{amount}').then(response => {
vm.corn = response.data;
}) },
// milliseconds we wait for user to stop typing.
500
) }, }
</script>
And here's the route (did a little editing, this updates now):
Route::post('/corn', function () {
$test = App\Resource::where('user_id', Auth::id())->update(['cornquant' => request('amount')]);
return $test;
});
Use an es6 arrow function in debounce to preserve this. Then remove var vm = this and assign to corn like this.corn = response.data.
And where are you initially calling getCorn?
Got everything sorted. Defining default values was the hardest part, but ended up being easy enough!
Here's the vue template file:
<template>
<div>Corn: <input v-model="corn" style="width: 50px;" /></div>
</template>
<script>
export default {
data: function() {
return {
items: 'not updated',
corn: '0'
} },
watch: { // whenever input amount changes, function will run
corn: function() {
this.getCorn()
} },
mounted: function() {
this.getVueItems(); //this will call the actual corn value to put as the default value
},
methods: {
getVueItems: function() {
axios.get('/testing').then(response => {
this.items = response.data;
this.corn = response.data.cornlq; //set initial value
}); },
getCorn: _.debounce(
function() {
var vm = this
axios.post('/corn', { //updates database
corn: this.corn,
}).then(response => {
vm.corn = response.data.cornlq; //keeps actual database value in input
}) },
2000
) }, }
</script>
And the route:
Route::post('/corn', function () {
App\Resource::where('user_id', Auth::id())->update(['cornlq' => request('corn')]); //update database with new amount
$result = App\Resource::where('user_id', Auth::id())->first(); //save all amounts to $result
return $result; //return result so I can update the vue
});
I am using the select2 for on of my search boxes. I'm getting the results from my URL but I'm not able to select an option from it. I want to use the 'product.productName' as the text to be shown after selection. Is there anything that I have missed out or any mistake that I have made. I have included select2.css and select2.min.js,jquery.js
function dataFormatResult(product) {
var markup = "<table class='product-result'><tr>";
markup += "<td class='product-info'><div class='product-title'>" + product.productName + "</div>";
if (product.manufacturer !== undefined) {
markup += "<div class='product-synopsis'>" + product.manufacturer + "</div>";
}
else if (product.productOptions !== undefined) {
markup += "<div class='product-synopsis'>" + product.productOptions + "</div>";
}
markup += "</td></tr></table>";
return markup;
}
function dataFormatSelection(product) {
return product.productName;
}
$(document).ready(function() {
$("#e7").select2({
placeholder: "Search for a product",
minimumInputLength: 2,
ajax: {
url: myURL,
dataType: 'json',
data: function(term,page) {
return {
productname: term
};
},
results: function(data,page) {
return {results: data.result_object};
}
},
formatResult: dataFormatResult,
formatSelection: dataFormatSelection,
dropdownCssClass: "bigdrop",
escapeMarkup: function(m) {
return m;
}
});
});
This is my resut_object
"result_object":[{"productName":"samsung galaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Silver;32GB"},{"productName":"samsung salaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Graphite;32GB"},{"productName":"samsung galaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Silver;16GB"}]
You are missing id attribute for result data. if it has not, it makes option "unselectable".
Example:
$('#e7').select2({
id: function(e) { return e.productName; },
});
Since I was using AJAX, what worked for me was returning something as the ID on processResults:
$(field).select2({
ajax: {
// [..] ajax params here
processResults: function(data) {
return {
results: $.map(data, function(item) {
return {
// proccessResults NEEDS the attribute id here
id: item.code,
// [...] other attributes here
foo: item.bar,
}
})
}
},
},
});
The id param can be a string related to the object property name, and must be in the root of the object. Text inside data object.
var fruits = [{code: 222, fruit: 'grape', color:'purple', price: 2.2},
{code: 234,fruit: 'banana', color:'yellow', price: 1.9} ];
$(yourfield).select2(
{
id: 'code',
data: { results: fruits, text: 'fruit' }
}
);
I have faced the same issue,other solution for this issue is:-
In your response object(In above response Product details object) must have an "id" as key and value for that.
Example:- Your above given response object must be like this
{"id":"1","productName":"samsung galaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Silver;32GB"}
SO you don't need this
id: function(object){return object.key;}
Dear fellow EXT enthusiasts,
I'm working on a project where I need an admin panel to edit job functions.
The grid is communicating to a MySQL database using Ext.Direct. It loads the data fine.
The grid shows the id and the function name
I added a RowEditing plugin to my grid for editting the function settings.
The problem is, when I try to commit the changes I get a tiny red triangle in the upper left corner of the grid without any error code in the console. The changes don't commit to the MySQL database.
The way my program works and loads the data:
This is my functionStore:
Ext.direct.Manager.addProvider(Ext.app.REMOTING_API);
Ext.define("MCS.store.FunctionStore",
{
extend: "Ext.data.Store",
requires: "MCS.model.Functions",
model: "MCS.model.Functions",
id: "FunctionStore",
proxy:
{
type: "direct",
api:
{
read: QueryDatabase.getFunctions,
create: QueryDatabase.createFunction,
update: QueryDatabase.updateFunction,
destroy: QueryDatabase.removeFunction,
}
},
});
In the controller: when the admin panel is rendered, the store gets loaded with the following function:
loadStore: function()
{
functionStore.load();
}
This is the grid where the functions are displayed:
var rowEditingFunctions = Ext.create("Ext.grid.plugin.RowEditing",
{
clicksToMoveEditor: 1,
autoCancel: false,
listeners: {
edit: function(editor,e,opt)
{
var grid = e.grid;
var record = e.record;
console.log(record.data.functionName);
var editedrecords = grid.getStore().getUpdatedRecords();
console.log(editedrecords);
}
}
});
var functionGrid = Ext.create("Ext.grid.Panel",
{
height: 500,
width: 800,
store: functionStore,
title:"List of Job Functions - double click to edit",
columns: [
{
dataIndex: "id",
width: 50,
text: "ID"
},{
dataIndex: "functionName",
flex: 1,
text: "Function",
field:
{
type: "textfield",
allowBlank: false
}
}],
plugins: [
rowEditingFunctions
],
dockedItems: [
{
xtype: "toolbar",
store: functionStore,
dock: "bottom",
items: [
{
iconCls: "add",
text: "Add",
handler: function()
{
rowEditingFunctions.cancelEdit();
var newRecord = Ext.create("App.model.Functions");
functionStore.insert(0, newRecord);
rowEditingFunctions.startEdit(0, 0);
var sm = functionGrid.getSelectionModel();
functionGrid.on("edit", function() {
var record = sm.getSelection()
functionStore.sync();
functionStore.remove(record);
functionStore.load();
});
}
}, {
iconCls: "delete",
text: "Delete",
handler: function()
{
rowEditingFunctions.cancelEdit();
var sm = functionGrid.getSelectionModel();
Ext.Msg.show(
{
title:"Delete Record?",
msg: "You are deleting a function permanently, this cannot be undone. Proceed?",
buttons: Ext.Msg.YESNO,
icon: Ext.Msg.QUESTION,
fn: function(btn)
{
if(btn === "yes")
{
functionStore.remove(sm.getSelection());
functionStore.sync();
}
}
});
}
}]
}]
});
As u can see I added a listener to the edit event of the RowEditing plugin, this displays the array of the edited record in console like it should.
4. And finally, this is the PHP code that updates the database:
public function updateFunction(stdClass $params)
{
$db = $this->__construct();
if ($stmt = $db->prepare("UPDATE functions SET functionName=? WHERE id=?"))
{
$stmt->bind_param('si', $functionName, $id);
$functionName = $params->functionName;
$id = (int) $params->id;
$stmt->execute();
$stmt->close();
}
return $this;
}
5. The weird part: once I've added one job function, I can edit all the other functions and those changes are committed to the database...
As a side note: I'm just a beginner in EXT, trying to learn it on my own, but I have been breaking my head on this issue for the last few days so I decided to ask you guys.
Thanks for your answers in advance!
I left the bug for what it was for a few weeks and started to look into it again this week.
I found a work around solution.
I've added the following code to my controller that controls the grids:
functionGrid.on('edit', function(editor, e)
{
e.store.sync();
});
Now when I update a record, the tiny red triangle still appears but after the e.store.sync() function is completed it disappears and the database table is updated.
Not a 100% clean solution, but it does the trick
If anyone has a better solution, please let me know
I've been trying for days to get this working and I just cannot figure out why when I have my view to destroy a model which belongs to a collection (which properly has a url attribute for the beginning fetch of models' data), only fires the destroy 'event' which is bubbled up to the collection for easy binding by my list view. But it does not ever send an actual DELETE request or any request to the server at all. Everywhere I look, I see everyone using either the collection's url attr, or urlRoot if the model is not connected to a collection. I've even tested before the actual this.model.destroy() to check the model < console.log(this.model.url());
I have not overwritten the destroy nor sync methods for backbone. Also each model does have an id attribute which is populated via the collection's fetch (from database records).
The destroy takes place in the list item view, and the collection's "destroy" event is bound in the list view. All that works well (the event handling), but the problem, again, is there's no request to the server.
I was hoping that backbone.js would do it automatically. That was what the documentation implies, as well as the numerous examples everywhere.
Much thanks to anyone who can give some useful input.
FYI: I'm developing on wampserver PHP 5.3.4.
ListItemView = BaseView.extend({
tagName: "li",
className: "shipment",
initialize: function (options) {
_.bindAll(this);
this.template = listItemTemplate;
this.templateEmpty = listItemTemplateEmpty;
},
events: {
'click .itemTag' : 'toggleData',
'click select option' : 'chkShipper',
'click .update' : 'update',
'click button.delete' : 'removeItem'
},
// ....
removeItem: function() {
debug.log('remove model');
var id = this.model.id;
debug.log(this.model.url());
var options = {
success: function(model, response) {
debug.log('remove success');
//debug.log(model);
debug.log(response);
// this.unbind();
// this.remove();
},
error: function(model, response) {
debug.log('remove error');
debug.log(response);
}
};
this.model.destroy(options);
//model.trigger('destroy', this.model, this.model.collection, options);
}
});
Collection = Backbone.Collection.extend({
model: Model,
url: '?dispatch=get&src=shipments',
url_put : '?dispatch=set&src=shipments',
name: 'Shipments',
initialize: function () {
_.bindAll(this);
this.deferred = new $.Deferred();
/*
this.fetch({
success: this.fetchSuccess,
error: this.fetchError
});
*/
},
fetchSuccess: function (collection, response) {
collection.deferred.resolve();
debug.log(response);
},
fetchError: function (collection, response) {
collection.deferred.reject();
debug.log(response);
throw new Error(this.name + " fetch failed");
},
save: function() {
var that = this;
var proxy = _.extend( new Backbone.Model(),
{
url: this.url_put,
toJSON: function() {
return that.toJSON();
}
});
var newJSON = proxy.toJSON()
proxy.save(
newJSON,
{
success: that.saveSuccess,
error: that.saveError
}
);
},
saveSuccess: function(model, response) {
debug.log('Save successful');
},
saveError: function(model, response) {
var responseText = response.responseText;
throw new Error(this.name + " save failed");
},
updateModels: function(newData) {
//this.reset(newData);
}
});
ListView = BaseView.extend({
tagName: "ul",
className: "shipments adminList",
_viewPointers: {},
initialize: function() {
_.bindAll(this);
var that = this;
this.collection;
this.collection = new collections.ShipmentModel();
this.collection.bind("add", this.addOne);
this.collection.fetch({
success: this.collection.fetchSuccess,
error: this.collection.fetchError
});
this.collection.bind("change", this.save);
this.collection.bind("add", this.addOne);
//this.collection.bind("remove", this.removeModel);
this.collection.bind("destroy", this.removeModel);
this.collection.bind("reset", this.render);
this.collection.deferred.done(function() {
//that.render();
that.options.container.removeClass('hide');
});
debug.log('view pointers');
// debug.log(this._viewPointers['c31']);
// debug.log(this._viewPointers[0]);
},
events: {
},
save: function() {
debug.log('shipments changed');
//this.collection.save();
var that = this;
var proxy = _.extend( new Backbone.Model(),
{
url: that.collection.url_put,
toJSON: function() {
return that.collection.toJSON();
}
});
var newJSON = proxy.toJSON()
proxy.save(
newJSON,
{
success: that.saveSuccess,
error: that.saveError
}
);
},
saveSuccess: function(model, response) {
debug.log('Save successful');
},
saveError: function(model, response) {
var responseText = response.responseText;
throw new Error(this.name + " save failed");
},
addOne: function(model) {
debug.log('added one');
this.renderItem(model);
/*
var view = new SB.Views.TicketSummary({
model: model
});
this._viewPointers[model.cid] = view;
*/
},
removeModel: function(model, response) {
// debug.log(model);
// debug.log('shipment removed from collection');
// remove from server
debug.info('Removing view for ' + model.cid);
debug.info(this._viewPointers[model.cid]);
// this._viewPointers[model.cid].unbind();
// this._viewPointers[model.cid].remove();
debug.info('item removed');
//this.render();
},
add: function() {
var nullModel = new this.collection.model({
"poNum" : null,
"shipper" : null,
"proNum" : null,
"link" : null
});
// var tmpl = emptyItemTmpl;
// debug.log(tmpl);
// this.$el.prepend(tmpl);
this.collection.unshift(nullModel);
this.renderInputItem(nullModel);
},
render: function () {
this.$el.html('');
debug.log('list view render');
var i, len = this.collection.length;
for (i=0; i < len; i++) {
this.renderItem(this.collection.models[i]);
};
$(this.container).find(this.className).remove();
this.$el.prependTo(this.options.container);
return this;
},
renderItem: function (model) {
var item = new listItemView({
"model": model
});
// item.bind('removeItem', this.removeModel);
// this._viewPointers[model.cid] = item;
this._viewPointers[model.cid] = item;
debug.log(this._viewPointers[model.cid]);
item.render().$el.appendTo(this.$el);
},
renderInputItem: function(model) {
var item = new listItemView({
"model": model
});
item.renderEmpty().$el.prependTo(this.$el);
}
});
P.S... Again, there is code that is referenced from elsewhere. But please note: the collection does have a url attribute set. And it does work for the initial fetch as well as when there's a change event fired for saving changes made to the models. But the destroy event in the list-item view, while it does trigger the "destroy" event successfully, it doesn't send the 'DELETE' HTTP request.
Do your models have an ID? If not, the HTTP request won't be sent. –
nikoshr May 14 at 18:03
Thanks so much! Nikoshr's little comment was exactly what I needed. I spent the last 5 hours messing with this. I just had to add an id to the defaults in my model.