Extjs 4.2 load form data with [] in name - javascript

I have a extjs form with has names like
udField[1]
udFIeld[2]
I can save it on server side without problems. But when i want to laod the form it just wont populate the value....
Here is on example from the ud dield:
{
labelSeparator: config.required == 1 ? ': <span style="color:red">*</span>' : ':',
allowBlank: config.required == 0,
emptyText: config.options.blankText,
xtype: 'textfield',
name: 'udFields[' + config.options.udFieldId + ']',
flex: 0,
fieldLabel: Ext.lang(config.display_name),
}
And here is how i load it:
Ext.getCmp('rootform').getForm().load({
url: 'ajax/Freetext/Article/LoadSingle',
waitMsg: Ext.lang('t_warenkorb_wird_geladen'),
params: {
cartarticle_id: cartarticleId,
sid: config.sid
},
success: function (form) {
some checks and other stuff
}
I get the correct response from the server to this is the response json data:
amount: "1"
cartarticle_id: "xxx"
catalogpartner_id_freetxt: "xxx"
delivery_date: "15.04.2015"
description_long: "test "
description_short: "test"
manufacturer_aid: "xxx"
manufacturer_name: "xxxxxx"
order_unit: "PAK"
price_amount: "122.12"
remarks: "test"
supplier_aid: "test"
udFields[123]: "test"
but the damn thing wont load no mather what.... anyone has some ideas???
ps here is the whole json string with obscured data:
{"success":true,"data":{"catalogpartner_id_freetxt":"12","description_short":"test","cartarticle_id":"12","amount":"1","order_unit":"PAK","price_amount":"122.12","delivery_date":"15.04.2015","description_long":"test ","remarks":"test","supplier_aid":"test","manufacturer_name":"Datenbank feiger Text (#todo)","manufacturer_aid":"Datenbank feiger Text (#todo)","udFields[123]":"test"},"debug":["11.05.2015 16:58:20.860232 params:Array\n(\n [cartarticle_id] => 312\n [sid] => 132\n)\n<br><BR>"]}

Well i could not figure out how to configure it. tried varios ways. In end i made a post sucess parser from an array....
Not pretty but only solution i could rely on....
success: function (form, data) {
if (data.result.data)
if (data.result.data.udFields) {
for (var key in data.result.data.udFields) {
var element = data.result.data.udFields[key];
var input = form.findField('udFields' + element.id);
if (input)
input.setValue(element.value);
}
}...

Related

Saving Only the changed record on a BackGrid grid?

I am in the process of learning Backbone.js and using BackGrid to render data and provide the end user a way to edit records on an Microsoft MVC website. For the purposes of this test grid I am using a Vendor model. The BackGrid makes the data editable by default (which is good for my purpose). I have added the following JavaScript to my view.
var Vendor = Backbone.Model.extend({
initialize: function () {
Backbone.Model.prototype.initialize.apply(this, arguments);
this.on("change", function (model, options) {
if (options && options.save === false) return;
model.url = "/Vendor/BackGridSave";
model.save();
});
}
});
var PageableVendors = Backbone.PageableCollection.extend(
{
model: Vendor,
url: "/Vendor/IndexJson",
state: {
pageSize: 3
},
mode: "client" // page entirely on the client side.
});
var pageableVendors = new PageableVendors();
//{ data: "ID" },
//{ data: "ClientID" },
//{ data: "CarrierID" },
//{ data: "Number" },
//{ data: "Name" },
//{ data: "IsActive" }
var columns = [
{
name: "ID", // The key of the model attribute
label: "ID", // The name to display in the header
editable: false, // By default every cell in a column is editable, but *ID* shouldn't be
// Defines a cell type, and ID is displayed as an integer without the ',' separating 1000s.
cell: Backgrid.IntegerCell.extend({
orderSeparator: ''
})
}, {
name: "ClientID",
label: "ClientID",
cell: "integer" // An integer cell is a number cell that displays humanized integers
}, {
name: "CarrierID",
label: "CarrierID",
cell: "number" // A cell type for floating point value, defaults to have a precision 2 decimal numbers
}, {
name: "Number",
label: "Number",
cell: "string"
}, {
name: "Name",
label: "Name",
cell: "string"
},
{
name: "IsActive",
label: "IsActive",
cell: "boolean"
}
];
// initialize a new grid instance.
var pageableGrid = new Backgrid.Grid({
columns: [
{
name:"",
cell: "select-row",
headercell: "select-all"
}].concat(columns),
collection: pageableVendors
});
// render the grid.
var $p = $("#vendor-grid").append(pageableGrid.render().el);
// Initialize the paginator
var paginator = new Backgrid.Extension.Paginator({
collection: pageableVendors
});
// Render the paginator
$p.after(paginator.render().el);
// Initialize a client-side filter to filter on the client
// mode pageable collection's cache.
var filter = new Backgrid.Extension.ClientSideFilter({
collection: pageableVendors,
fields: ['Name']
});
// REnder the filter.
$p.before(filter.render().el);
//Add some space to the filter and move it to teh right.
$(filter.el).css({ float: "right", margin: "20px" });
// Fetch some data
pageableVendors.fetch({ reset: true });
#{
ViewBag.Title = "BackGridIndex";
}
<h2>BackGridIndex</h2>
<div id="vendor-grid"></div>
#section styles {
#Styles.Render("~/Scripts/backgrid.css")
#Styles.Render("~/Scripts/backgrid-select-all.min.css")
#Styles.Render("~/Scripts/backgrid-filter.min.css")
#Styles.Render("~/Scripts/backgrid-paginator.min.css")
}
#section scripts {
#Scripts.Render("~/Scripts/underscore.min.js")
#Scripts.Render("~/Scripts/backbone.min.js")
#Scripts.Render("~/Scripts/backgrid.js")
#Scripts.Render("~/Scripts/backgrid-select-all.min.js")
#Scripts.Render("~/Scripts/backbone.paginator.min.js")
#Scripts.Render("~/Scripts/backgrid-paginator.min.js")
#Scripts.Render("~/Scripts/backgrid-filter.min.js")
#Scripts.Render("~/Scripts/Robbys/BackGridIndex.js")
}
When the user edits a row, it successfully fires the hits the model.Save() method and passes the model to the save Action, in this case BackGridSave and it successfully saves the record that changed, but seems to save all of the vendors in model when only one of the vendors changed. Is there a way from the JavaScript/Backbone.js/BackGrid to only pass one Vendor - the vendor that changed?
Update: I realized that it is not sending every vendor, but it is sending the same vendor multiple times as though the change event was firing multiple times.
I guess I answered my own question. Well, at least I am getting the desired result. I just added a call to off after the first on. Seems like this would not be necessary though.
var Vendor = Backbone.Model.extend({
initialize: function () {
Backbone.Model.prototype.initialize.apply(this, arguments);
this.on("change", function (model, options) {
if (options && options.save === false) return;
model.url = "/Robbys/BackGridSave";
model.save();
model.off("change", null, this); // prevent the change event from being triggered many times.
});
}
});

UI-Select2 binding to object instead of property of object

I am using ui-select2, version 3.5.2, trying to do a single select, type-ahead and retrieve from REST api, drop down list.
It looks like it is working except for one major issue, which is that, the ng-model's property gets set to an object {Id: "some id", text: "some text"} instead of the actual Id property. I cannot figure out how to tell ui-select2 control to set the ng-model property to the "Id" field of the object, instead of the whole object.
I have tried various hacks with watchers but didnt get anywhere. I am sure there is something that I am missing because this is something that should be possible easily.
Here is my javascript code:
$scope.selectOptions = {
placeholder: '- Select Value -',
allowClear: true,
minimumInputLength: 2,
initSelection: function (element, callback)
{
if ($scope.myobj && $scope.myobj.Id && $scope.myobj.Id !== '00000000-0000-0000-0000-000000000000')
{
$.ajax("../../api/objs/" + $scope.myobj.Id).done(function (data) {
var res = $(data).map(function (i, o) {
return {
id: o.Value,
text: o.Display
};
}).get();
callback(res[0]);
});
}
},
ajax:
{
type: "GET",
url: function (term) {
return ["../../api", "objs", encodeURIComponent(term)].join("/");
},
dataType: "json",
contentType: "application/json",
cache: false,
results: function (data, page) {
return {
results: $(data).map(function (i, o) {
angular.extend(o, {
id: o.Value,
text: o.Display
});
return o;
}).get()
};
}
}
}
Here is my html code:
<div ui-select2='selectOptions' ng-model="myobj.Id" style="width:215px" />
I got around this by binding to a separate property and then adding a ng-change on my div and syncing the binding property's id field to actual property on my object.

Select2: Update option after selecting new tag

I implemented a tagging system where you can choose from existing tags or add new tags. After a new tag has been selected it will persisted using an AJAX call.
For achieving this I use the callback createTag and the event select2:select. Because I like to create the tag only when it is selected I do an AJAX call for this if the event select2:select gets triggered.
The problem is that I need to update the already created option of select2 with the ID I get from persisting my new tag to the database. What's the cleanest solution for this?
Here's what I have:
$('select.tags').select2({
tags: true,
ajax: {
url: '{{ path('tag_auto_complete') }}',
processResults: function (data) {
return {
results: data.items,
pagination: {
more: false
}
};
}
},
createTag: function (tag) {
return {
id: tag.term, // <-- this one should get exchanged after persisting the new tag
text: tag.term,
tag: true
};
}
}).on('select2:select', function (evt) {
if(evt.params.data.tag == false) {
return;
}
$.post('{{ path('tag_crrate_auto_complete') }}', { name: evt.params.data.text }, function( data ) {
// ----> Here I need to update the option created in "createTag" with the ID
option_to_update.value = data.id;
}, "json");
});
My problem was that I did not add the new tag as an <option> tag to the native select field.
This is necessary because select2 checks for the values set trough select2.val(values) if an <option> tag with this value does exist. If not select2 silently throws the value out of the array and sets the array of values which have a corresponding option tag in the underlying select field.
So this is how it works correct now (for select2 4.0.x):
$('select.tags').select2({
tags: true,
ajax: {
url: '{{ path('tag_auto_complete') }}',
processResults: function (data) {
return {
results: data.items,
pagination: {
more: false
}
};
}
},
createTag: function (tag) {
return {
id: tag.term,
text: tag.term,
tag: true
};
}
}).on('select2:select', function (evt) {
if(evt.params.data.tag == false) {
return;
}
var select2Element = $(this);
$.post('{{ path('tag_crrate_auto_complete') }}', { name: evt.params.data.text }, function( data ) {
// Add HTML option to select field
$('<option value="' + data.id + '">' + data.text + '</option>').appendTo(select2Element);
// Replace the tag name in the current selection with the new persisted ID
var selection = select2Element.val();
var index = selection.indexOf(data.text);
if (index !== -1) {
selection[index] = data.id.toString();
}
select2Element.val(selection).trigger('change');
}, 'json');
});
The minimal AJAX response (JSON format) has to look like this:
[
{'id': '1', 'text': 'foo'},
{'id': '2', 'text': 'bar'},
{'id': '3', 'text': 'baz'}
]
You may add additional data to each result for let's say own rendering of the result list with additional data in it.
Just to update:
The new syntax is
e.params.args.data.id
not
e.params.data.id

How do I create a delete button on every row in slickgrid with confirmation?

As the title said it, how do I do it?, I am using this button created by jiri:
How do i create a delete button on every row using the SlickGrid plugin?
when I add an if(confirmation(msg)) inside the function it repeats me the msg ALOT
maybe its because i refresh-ajax the table with each modification.
ask me if you need more info, I am still noob here in stackoverflow :P
(also if there is someway to "kill" the function)
here is the button, iam using(link) i added the idBorrada to check whetever the id was already deleted and dont try to delete it twice, also here is a confirm, but when i touch cancel it asks me again.
$('.del').live('click', function(){
var me = $(this), id = me.attr('id');
//assuming you have used a dataView to create your grid
//also assuming that its variable name is called 'dataView'
//use the following code to get the item to be deleted from it
if(idBorrada != id && confirm("¿Seguro desea eleminarlo?")){
dataView.deleteItem(id);
Wicket.Ajax.ajax({"u":"${url}","c":"${gridId}","ep":{'borrar':JSON.stringify(id, null, 2)}});
//This is possible because in the formatter we have assigned the row id itself as the button id;
//now assuming your grid is called 'grid'
//TODO
grid.invalidate();
idBorrada= id;
}
else{
};
});
and i call the entire function again.
hope that help, sorry for the grammar its not my native language
Follow these steps,
Add a delete link for each row with of the columns object as follows,
var columns =
{ id: "Type", name: "Application Type", field: "ApplicationType", width: 100, cssClass: "cell-title", editor: Slick.Editors.Text, validator: requiredFieldValidator, sortable: true },
{ id: "delete", name: "Action", width: 40, cssClass: "cell-title", formatter: Slick.Formatters.Link }
];
Add a Link Formatter inside slick.formatters.js as follows,
"Formatters": {
"PercentComplete": PercentCompleteFormatter,
"YesNo": YesNoFormatter,
"Link": LinkFormatter
}
function LinkFormatter(row, cell, value, columnDef, dataContext) {
return "<a style='color:#4996D0; text-decoration:none;cursor:pointer' onclick='DeleteData(" + dataContext.Id + ", " + row + ")'>Delete</a>";
}
Add the following delete function in javascript
function DeleteData(id, rowId) {
var result = confirm("Are you sure you want to permenantly delete this record!");
if (result == true) {
if (id) {
$.ajax({
type: "POST",
url: "DeleteURL",
data: { id: id },
dataType: "text",
success: function () {
},
error: function () {
}
});
}
dataView.deleteItem(id);
dataView.refresh();}
}

Extjs - Dynamically generate fields in a FormPanel

I've got a script that generates a form panel:
var form = new Ext.FormPanel({
id: 'form-exploit-zombie-' + zombie_ip,
formId: 'form-exploit-zombie-' + zombie_ip,
border: false,
labelWidth: 75,
formBind: true,
defaultType: 'textfield',
url: '/ui/modules/exploit/new',
autoHeight: true,
buttons: [{
text: 'Execute exploit',
handler: function () {
var form = Ext.getCmp('form-exploit-zombie-' + zombie_ip);
form.getForm().submit({
waitMsg: 'Running exploit ...',
success: function () {
Ext.beef.msg('Yeh!', 'Exploit sent to the zombie.')
},
failure: function () {
Ext.beef.msg('Ehhh!', 'An error occured while trying to send the exploit.')
}
});
}
}]
});
that same scripts then retrieves a json file from my server which defines how many input fields that form should contain. The script then adds those fields to the form:
Ext.each(inputs, function(input) {
var input_name;
var input_type = 'TextField';
var input_definition = new Array();
if(typeof input == 'string') {
input_name = input;
var field = new Ext.form.TextField({
id: 'form-zombie-'+zombie_ip+'-field-'+input_name,
fieldLabel: input_name,
name: 'txt_'+input_name,
width: 175,
allowBlank:false
});
form.add(field);
}
else if(typeof input == 'object') {
//input_name = array_key(input);
for(definition in input) {
if(typeof definition == 'string') {
}
}
} else {
return;
}
});
Finally, the form is added to the appropriate panel in my interface:
panel.add(form);
panel.doLayout();
The problem I have is: when I submit the form by clicking on the button, the http request sent to my server does not contain the fields added to the form. In other words, I'm not posting those fields to the server.
Anyone knows why and how I could fix that?
Your problem is here:
id: 'form-exploit-zombie-'+zombie_ip,
formId: 'form-exploit-zombie-'+zombie_ip,
what you are doing is that you are setting the id attribute of the form panel and the id attribute of the form (form tag) to the same value. Which means that you have two elements with the same id and that is wrong.
Just remove this line
formId: 'form-exploit-zombie-'+zombie_ip,
and you should be fine.
Did you check the HTTP Request parameter for the form values?
If you server side is in PHP, what do you get from response by passing any field name? For example, if one of your input name was "xyz" what do you get by
$_POST[ 'txt_xyz' ]

Categories

Resources