I have a statemodel like this:
var stateModel = {
StateId: ko.observable(0),
StateName: ko.observable('').extend({ required: true }).extend({ pattern: { message: 'Enter only Text', params: '^[a-zA-Z ]*$'} }),
ShortName: ko.observable('')
.extend({ required: true })
.extend({ pattern:
{ message: 'Enter only Text', params: '^[a-zA-Z ]*$'}
}),
IsActive: ko.observable(true),
CountryId: ko.observable().extend({ required: true })
}
And i am posting it by converting into json string by following :
var args=JSON.stringify({argBO: jQuery.parseJSON(ko.toJSON(self.StateModel))});
after this i want to push this to my observable array StateList() ,so i am converting it into objects and pushing it like:
var model = jQuery.parseJSON(ko.toJSON(self.StateModel));
self.StatesList.push(model);
My args will look like this:
{"argBO":
{ "StateId":0,
"StateName":"jjhj",
"ShortName":"jjj",
"IsActive":true,
"CountryId":8,
"errors":[],
"CountryName":"Antigua and Barbud"
}
}
If i could remove the argBO From above i can directly push the 'args' rather than self.StateModel, again by converting args into objects.
self.StatesList.Push(args);
I tried like this :
jQuery.parseJSON(args(jQuery.parseJSON(argBO)))
jQuery.parseJSON(args(jQuery.parseJSON[argBO]))
jQuery.parseJSON(args[argBO]))
But none of them working please anybody tell me!!
You can try this:
var JSONargs = jQuery.parseJSON(ko.toJSON(self.StateModel));
OR if you use the knockout.mapping.js plugin:
var JSONargs = ko.mapping.toJS(self.StateModel);
When you want to post it, you can do:
$.ajax({data: JSON.stringify({ argBO: JSONargs });
And then your push could be like
self.StatesList.Push(JSONargs);
Related
I am trying to add a hidden field for the user registration. The problem is not with the field itself but with its value. I want to parse it a default value. This is my code:
Accounts.ui.config({
requestPermissions: {},
extraSignupFields: [{
fieldName: 'name',
fieldLabel: 'Name',
inputType: 'text',
visible: true,
validate: function(value, errorFunction) {
if (!value) {
errorFunction("Please write your first name");
return false;
} else {
return true;
}
}
},{
fieldName: 'status',
fieldLabel: 'Status',
inputType: 'text',
value: 'somevalue',
visible: false,
}]
});
I want to add the value to the field 'status'.
Actually, I found the answer. The option is the following code in the
server folder:
Accounts.onCreateUser(function(options, user) {
if (options.profile) {
user.profile = options.profile;
}
user.profile.status = "sth";
return user;
});
Looking at the implementation of signup in that package, there is no way to set a default value. The code just creates an object in signup() and grabs whatever existing values from the form that it can.
I use Formly for creating my forms in angularJS
This is my field
$scope.postFields = [
{
key: 'title',
type: 'input',
templateOptions: {
label: "Title",
// required: true,
minlength: 2,
},
validation: {
messages: {
required: function(viewValue, modelValue, scope) {
return scope.to.label + ' is required'
}
}
}
}
]
and I'm trying to access my fields as follows
function failure(response) {
console.log("failure", response)
_.each(response.data, function(errors, key) {
_.each(errors, function(e) {
$scope.form[key].$dirty = true;
$scope.form[key].$setValidity(e, false);
});
});
}
my formly form
<formly-form form="postForm" model="model" fields="postFields" class="col-md-4">
<button type="submit" class="btn btn-primary" ng-click="addPost()">Submit</button>
</formly-form>
but of course I'm getting this error:
TypeError: Cannot read property 'title' of undefined
it's on this line
$scope.form[key].$dirty = true;
do anyone of you know how to reference created formly fields the right way?
If you want to be able to reference the fields from the form, you could provide a name attribute to your fields. The name is generated by default. It's one of the nice things that angular-formly provides (you don't have to think about it). But if you want to reference it directly with a specific key (as you are) then you'd be best served by providing one yourself.
So you'd do something like this:
$scope.postFields = [
{
key: 'title',
name: 'title',
type: 'input',
templateOptions: {
label: "Title",
// required: true,
minlength: 2,
},
validation: {
messages: {
required: function(viewValue, modelValue, scope) {
return scope.to.label + ' is required'
}
}
}
}
]
Alternatively, you could create a fieldTransform to do this automatically (just assign the name the same as the key). Or in your error handler, you could look up the NgModelController from the field's formControl property like this:
function handleError(fields, response) {
_.each(fields, function(field) {
if (response.data[field.key]) {
field.formControl.$setDirty()
_.each(response.data[field.key], function(e) {
field.formControl.$setValidity(e, false)
})
}
})
}
That's probably the best solution :-) Good luck!
I have a backbone model:
App.Models.Education = Backbone.Model.extend({
schema: {
university: {
type: 'Text',
validators: ['required'],
editorAttrs: {placeholder: 'Test placeholder'}
},
info: {type: 'Text'},
desc: {type: 'Text'}
})
and extend it:
App.Models.HighSchool = App.Models.Education.extend({
initialize: function () {
//code to change placeholder
this.set({education_type: init_parameters.school});
}
});
How to change the placeholder text in "university" field of HighSchool?
I wouldn't recommend setting up your models that way. You should try to avoid nesting attributes because of the exact same issue you're having. It becomes hard to change one particular field.
Instead, can you do something like:
App.Models.Education = Backbone.Model.extend({
defaults: { // backbone keyword to have default model attributes
type: 'Text',
validators: ['required'],
editorAttrs: {placeholder: 'Test placeholder'
}
});
App.Models.HighSchool = App.Models.Education.extend({
initialize: function () {
//code to change placeholder
this.set('editorAttrs', {placeholder: 'new placeholder'});
this.set('education_type', init_parameters.school);
}
});
Mongoose findOne function call does nothing and I am in trouble again. Callback is not never returned...
schema.js file:
var schemaSizeGroup = new Schema({
sizeGroupId : {type: Number, required: true, index: true, index: { unique: true }}
,sizeGroupName : {type: String, required: true, trim: true, index: { unique: true }}
,sizeGroupValues : {type: String, required: true, trim: true }
,active : {type: Boolean, default: true }
}, { collection: 'sizegroup' }).index({sizeGroupId : 1});
module.exports ={
SizeGroup : mongoose.connection.model('SizeGroup', schemaSizeGroup),
}
index.js file:
findDocumentById : function(sGroupId, callback){
winston.info(" Trying to select!");
model.SizeGroup.findOne( {sizeGroupId : sGroupId} ,function(err, sGroup) {
winston.info(" Select done:");
winston.info(JSON.stringify(sGroup,null,2));
if(!err) {
if(!sGroup) {
callback(new Error(" No SizeObject Found for Id:" + sizeGroupId));
} else { callback(null, sGroup); }
}
else {
callback(err);
}
});
}
}
selectin data using mongo client returns correct data nicely:
db.sizegroup.find({sizeGroupId : 6});
When using mongoose.set('debug', true) output looks like:
Mongoose: sizegroup.findOne({ sizeGroupId: 6 }) { fields: undefined }
I have active mongoose connection, because all the previous insert statements have been successful.
Am I doing something wrong?
It was a callback problem in program flow. Clear case of pure stupidity....
So, this is what my model looks like (represented by fixture data):
var posts = [{
id: 'b026324c6904b2a9',
title: "My new front door",
author: { name: "Matthieu" },
date: new Date('2013-10-28T12:19:30.789'),
status: 'new',
hidden_message: "hidden1"
}, {
id: '26ab0db90d72e28a',
title: "Best pizza in town",
author: { name: "Harry" },
date: new Date('2013-10-28T12:19:30.789'),
status: '',
hidden_message: "hidden2"
}, {
id: '6d7fce9fee471194',
title: "Skateboard dreamland",
author: { name: "Matthieu" },
date: new Date('2013-10-28T12:19:30.789'),
status: 'solved',
hidden_message: "hidden3"
}, {
id: '48a24b70a0b37653',
title: "my house looks like a pumpkin",
author: { name: "Harry" },
date: new Date('2013-10-28T12:19:30.789'),
status: '',
hidden_message: "hidden4"
}];
My route:
App.IndexRoute = Ember.Route.extend({
model: function() {
return posts;
}
});
And, I'd like to be able to display a certain piece of HTML in the template if the corresponding post is new, a different one if it's solved, and nothing if the status is blank. It seems to me as if the best way to do this is using an {{#if}} helper, but that doesn't do equality comparisons, it can only take a boolean variable. So, I'd like to do something like this:
App.IndexController = Ember.ArrayController.extend({
isNew: function(val) {
if(this.get('currentitem.status') === 'new') {
return true;
}
return false;
}.property('isNew')
});
But I can't find out how to select the item being currently accessed by {{#each}} in the template. Is this even possible, and if yes, how do I do it (or something similar)?
Thanks all!
The correct way to do this is to create an itemcontroller that helps you by providing a controller per item in your collection.
App.IndexController = Ember.ArrayController.extend({
itemController: "PostItem",
});
App.PostItemController = Ember.ObjectController.extend({
isNew: function() {
if(this.get('status') === 'new') {
return true;
}
return false;
}.property('status')
});
Then in your handlebar template you can just call {{isNew}} in the {{#each}}-context.
I've put up a working fiddle that you can test it out in.
http://jsfiddle.net/LordDaimos/v8NR3/1/
Best way would probably be to wrap each post in an object that has the isNew method, like this:
var postObject = Ember.Object.extend({
isNew: function() {
if(this.get('status') === 'new') {
return true;
}
return false;
}.property('status')
});
App.IndexRoute = Ember.Route.extend({
model: function() {
return posts.map(function(post){
return postObject.create(post);
});
}
});
this way you could query on each post.