how to make view (form)from json using angular? - javascript

I am trying to make view from json .When I have array of objects .I am able to make view and validate that view .
If I have this array of object ,in that case I make able to view ,
check plunker
http://plnkr.co/edit/eD4OZ8nqETBACpSMQ7Tm?p=preview
[{
type: "email",
name: "email",
required:true
}, {
type: "text",
name: "name",
required:true
}, {
type: "number",
name: "phonenumber",
required:true
}, {
type: "checkbox",
name: "whant to check"
},
{
type: "url",
name: "server Url"
}];
Now the problem occurred when i have json object .I need to show view from json object .I don't know from where I will start work
I have this json
"displayName": display the name of label which is from of input text
field.
inputValues :represent the type of tmput filled .if it is number then
user fill only number , text then user only fill number ,email then
user fill email , if it switch then it is drop down with given
option.
"required" give if field is required or not ?

Assuming your JSON is coming from a configuration file or a service, you can start by obtaining the JSON as a JSON object:
angular.module('myapp', [])
.controller('MyController', ['$scope', function($scope) {
$scope.outputs = {};
$scope.rawInput = JSON.parse( '{"studentName": "abc", \
"input": {\
"loginUser": {\
"displayDetail": "UserId for login.",\
"displayName": "Login User Id*",\
"inputType": "TEXT",\
(I had to escape returns to allow the pretty printed JSON string to be parsed)
Once you have that, you are nearly there. Now you can just go the level of JSON that you require and construct your inputs array:
$scope.formInputs = $scope.rawInput['input'];
$scope.inputs = [];
angular.forEach($scope.formInputs, function(value, key) {
/* do something for all key: value pairs */
$scope.inputs.push({"type":value.inputType.toLowerCase(),"name":value.name,"required": value.required})
});
Note you should probably do some error checking here - for the purposes of this example, I don't use any. Here is a working plnkr that demonstrates this code.
I haven't got it all to work - you'll have to construct your select or radio button inputs, but I think you should be able to take it from here.
EDIT I have undated the plnkr to make it public

Related

How to make Input->value->type->search dynamic?

Usually a regular person's name does not contain numbers, so I added this search property to prevent numbers with RegEx to my Input element:
type: new sap.ui.model.type.String({}, { search: "^[^0-9]+$" })
But numbers should be allowed for a company's name. So how can I make this search value dynamic?
To visualize it:
"dwd3" should be invalid when it's anything other than "Company"
"dwd3" should be valid when it's a "Company"
Here's my minimal example - what I've tried so far is commented out, since it didn't work (resulted in numbers being valid at all times).
// Set data model
let data = {
"salutation": "Company",
"name": ""
};
let oModel = new sap.ui.model.json.JSONModel();
oModel.setData(data);
// Create page
let oPage = new sap.m.VBox();
oPage.setModel(oModel);
// Add salutation input
oPage.addItem(
new sap.m.Input({
value: {
path: "/salutation"
}
})
);
// Add name input
oPage.addItem(
new sap.m.Input({
value: {
type: new sap.ui.model.type.String({}, {
minLength: 2,
maxLength: 40,
search: "^[^0-9]+$"
/* not working...
search: {
parts: [
"/salutation",
],
formatter: (salutation) =>
salutation === "Company" ? "^.*$" : "^[^0-9]+$"
}
*/
}),
path: "/name",
},
required: true,
})
);
// Attach validation handlers
sap.ui.getCore().attachValidationError(function(oEvent) {
oEvent.getParameter("element").setValueState(sap.ui.core.ValueState.Error);
});
sap.ui.getCore().attachValidationSuccess(function(oEvent) {
oEvent.getParameter("element").setValueState(sap.ui.core.ValueState.None);
});
// Insert page
oPage.placeAt("content");
<script id='sap-ui-bootstrap' type='text/javascript' src='https://sapui5.hana.ondemand.com/resources/sap-ui-core.js' data-sap-ui-libs="sap.m,sap.ui.commons,sap.ui.table" data-sap-ui-theme="sap_bluecrystal">
</script>
<body class='sapUiBody'>
<div id='content'></div>
</body>
If the validation rule of one field depends on the value of another field, you could use events like change (with or without valueLiveUpdate=true) for validation.
A type should be something that does not depend on external life.
Another thing you could do is reacting on change event of your salutation field and exchange the type of the input field for the name (depending on the value of salutation)
PS: (edit) to be hontest, I wouldn't restrict a name field to anything that it may or may not contain. Depending on the country specific laws you may be allowed to use digits...

How To Retrieve More Than One "GetValue" From JSON/AJAX search

Ok, I'm struggeling with JSON, AJAX, Javascript and PHP.
Well, actually its only Javascript.
I want to have a input field which operates as a AutoSearch field.
I am using currently EasyAutoComplete.
But that doesnt really matter. What does matter is, that I have to choose one type from the JSON array to be searched. But I want to search both.
Just to make things clear:
- the user should be able to type in "abc" and "123" and find either the number "123456" or "School abc".
- When the user clicks on the result, in both cases the field value should be the number.
Javascript:
$(document).ready(function(){
var options = {
url: function(phrase){
console.log("autocomplete/autocomplete.php?term="+phrase);
return "autocomplete/autocomplete.php?term="+phrase;
},
highlightPhrase: false,
getValue: "instanz_id",
template: {
type: "description",
fields: {
description: "schulname"
}
},
list: {
hideAnimation: {
type: "slide",
time: 400,
callback: function(){}
},
match:{
enabled: true
}
}
};
$("#autocomplete").easyAutocomplete(options);
});
My database structure looks like:
"instanz_id", "schulname"
"123456", "DemoSchule"
Right now, if I type in "123" my JSON return string looks like this:
[{"instanz_id":"123456","schulname":"DemoSchule"}]
And my searchlist: "123456 - DemoSchule". When I click on it, 123456 is the new value of the input field.
How can I get the same item in the searchlist when typing e.g. "Dem" ?
I can change the getValue to "schulname" but then I cannot search using the number...
Can please someone send me in the right direction?

How can I make a field in a meteor Simple Schema equal to a js variable and still let the user fill out the rest of the simple schema?

I am making a meteor web app where the user will click on a html button. Once this button is clicked, the user needs to be directed to another page with some forms generated by a meteor simple schema package. The first field in the simple schema needs to automatically be given a string value of "hello" and then the rest of the fields in the simple schema will be filled out by the user with the input fields on the page. What I am unsure about is how to get the first value automatically set to this string value. Here is some of the code I have:
The simple schema declaration:
LobbySchema = new SimpleSchema({
game: {
type: String,
label: "Game"
},
console: {
type: String,
label: "Console"
},
players: {
type: Number,
label: "Players"
},
mic: {
type: Boolean,
label: "Mic"
},
note: {
type: String,
label: "Note"
},
gamertag: {
type: String,
label: "Gamertag"
},
createdAt: {
type: Date,
label: "Created At",
autoValue: function(){
return new Date()
},
autoform: {
type: "hidden"
}
}
});
The first field there in the schema "game" needs to be given the value "hello" when the html button is clicked. Right now I can assign that value to a javascript variable using the button by having an onclick function:
function getElementText(elementID){
var elementText = "hello";
}
The button would call the getElementText function and have the elementText variable equal "hello". Now I need to assign the the first field in the simple schema to this variable value, "hello", then have it so the user can now fill out the rest of the schema with the input fields, automatically generated into the html with this code:
{{> quickForm collection="Lobby" id="insertLobbyForm" type="insert" class="newLobbyForm"}}
If you do not feel like providing the answer (maybe it happens to be more complicated than I think) then I would be very happy to receive a link to a site that might help me with this. I am also very willing to explain anything about the question if I did not explain the situation well enough above.
You can use the AutoForm hooks like this:
AutoForm.hooks({
app_create: {
before: {
method: function (doc) {
// Do whatever assignment you need to do here,
// like doc['game'] = "hello"; //then
return doc;
}
},
onSuccess: function (formType, result) {
},
onError: function (formType, error) {
}
}
});
Where here app_create is the id of the form you're sending with Autoform.

Meteor : Iterate through array of Objects inside an Object

I'm currently trying to iterate through an array of Objects inside an Object.
I have my Collection "Proposals", and this is the corresponding Schema :
Schemas.ProposalsSchema = new SimpleSchema({
'content': {
type: String,
max: 140
},
'parties': {
type: [Object],
autoform : {
type: "select-multiple"
}
},
'parties.$._id': {
type: Object,
optional: true
},
'parties.$._id._str': {
type: String
},
'parties.$.name': {
type: String
}
});
I would like to iterate through the array of parties inside one of my template. I tried this :
{{#each proposals}}
<p>{{content}}</p>
<p>{{#each parties}} {{this.name}} {{/each}}</p>
{{/each}}
The content is displayed, but not the name of the different parties. Here's my template helper :
Template.proposalsIndex.helpers({
proposals: () => Proposals.find().fetch()
});
Do you know what do i do wrong?
Thank you in advance.
The code you posted looks ok.
Things you need to check are:
Is the "parties" field populated in a database? (you can run Proposals.find().fetch() in a meteor shell to check it).
If not, find out why it is not populated.
Is the "parties" field published to client? (you can run Proposals.find().fetch() in a browser console and see the results).
If not, check your publication.

how to show different message on required and invalid?

can you please tell me how to show different message on required and invalid ?In other word .make a form from json using plugin .In that there are some required parameter .and some I need to validate example "Email".When user press "submit" button if user did not fill the field it show "this field is required" .and if user fill the value but not same patten than it say "invalid value".can we show different message as different situation .
i used this plugin
https://github.com/Textalk/angular-schema-form/blob/master/docs/index.md#validation-messages
and I make this plunker
http://plnkr.co/edit/ZNJO3x3IqajjdMNStJMF?p=preview
angular.module('test',['schemaForm']).controller('FormController', function($scope,$http){
$scope.schema = {
type: "object",
properties: {
name: { type: "string", minLength: 2, title: "Name", description: "Name or alias" ,required:true,"default": "dddd"},
"student": { type: "string", title: "studentname", description: "Name or student" ,required:false},
"email": {
"title": "Email",
"type": "string",
"pattern":"\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*",
"description": "Email will be used for evil.",
required:true
},
title: {
type: "string",
required:true,
enum: ['dr','jr','sir','mrs','mr','NaN','dj'],
}
}
};
$scope.form = [
"*",
{
type: "submit",
title: "Save"
}
];
As you may read from the official angular-schema-form documentation
Per default all error messages comes from the schema validator tv4, this might or might not work for you. If you supply a validationMessage property in the form definition, and if its value is a string that will be used instead on any validation error.
If you need more fine grained control you can supply an object instead with keys matching the error codes of tv4. See tv4.errorCodes
Ex.
{
key: "address.street",
validationMessage: {
tv4.errorCodes.STRING_LENGTH_SHORT: "Address is too short, man.",
"default": "Just write a proper address, will you?" //Special catch all error message
}
}
You can also set a global validationMessage in formDefaults see Global Options.
So for more error messages, visit this link
Here is a great blog article that should answer your question: http://www.thebhwgroup.com/blog/2014/08/designing-html-forms-angularjs-part-1/
In particular, check out part 3 "Validation Messages and Styling".
From the article,
<span class="validation-message" ng-show="contactForm.firstName.$error.maxlength">Max length 20</span>
Where the ng-form is named contactForm and the element in question is named firstName. This puts the form on the scope and you can then traverse that to get the errors, and show an error message specifically for each error.

Categories

Resources