Getting Sitecore Field with Web API - javascript

I have a question regarding the Sitecore Item Web API.
I have this JSON extract result when I call my Sitecore Web API:
{"statusCode":200,
[...]
"Version":1,
"Fields":{
"{0DE95AE4-41AB-4D01-9EB0-67441B7C2450}":{
"Name":"Phone number",
"Type":"Single-Line Text",
"Value":"XXXX"},
"{FA170F50-43FA-49B7-9AB1-9B4047DDBC2C}":{
"Name":"Fax",
"Type":"Number",
"Value":"YYYYYY"}
What I would like to do is to get the phone number Value field, or the Fax value field, directly, without looping through each GUID testing if the Name == "Phone Number" and then getting the Value etc...
I already have this JavaScript code but it is with this foreach loop, and it's not really fast.
function extractPhoneNumber(siteCoreFieldsList) {
var phoneNumberFieldValue;
$jq.each(siteCoreFieldsList, function (index, value) {
if (value.Name == "Phone number") {
phoneNumberFieldValue = value.Value;
}
});
return phoneNumberFieldValue;
}
Anyone has a work around or something more clean ?
Thanks a lot for your help. Regards.

In terms of a "best practice", you should be storing the field IDs somewhere any using them to get to the value.
However, given you're already creating function with the specific purpose of getting a value you could place the IDs there.
function extractFax(sitecoreFieldList){
return sitecoreFieldList['{FA170F50-43FA-49B7-9AB1-9B4047DDBC2C}'] || '';
}
function extractPhoneNumber(sitecoreFieldList){
return sitecoreFieldList['{0DE95AE4-41AB-4D01-9EB0-67441B7C2450}'] || '';
}

Related

Optimized search bar filter in reactjs

I have implemented search filter in reactjs, but whenever I add space in the string, it doesn't show the existing product also.
For eg: I have Values like: "Iphone details", "Samsung phone deatils". If I enter "Iphone", I'll get the searched string as "Iphone details", but If i hit "space" after "IPhone", I'll not get the "Iphone details" but will get no result found. Can anyone help me in making optimized search for my react app.
const searchFilter = this.state.details.filter(
(data) => {
if (this.state.searchStr == null) return true;
else if (
data.name.includes(this.state.searchStr) ||
data.title.includes(this.state.searchStr)
) {
return data;
}
}
);
Can anyone help me with what's wrong with the code.
When doing comparison between saved values and user typed value, it is good to bring them to the same level, as much as you possibly can. This means that we could run the user's search and the item's value through a few normalizers. Take a look at the following modified code:
const searchFilter = this.state.details.filter(
(data) => {
if (this.state.searchStr == null) return true;
else if (
data.name.toLowerCase().trim().includes(this.state.searchStr.trim().toLowerCase()) ||
data.title.toLowerCase().trim().includes(this.state.searchStr.trim().toLowerCase())
) {
return data;
}
}
);
Functions I've added are:
.toLowerCase()
.trim()
What these do is normalize both the search input and data.name and data.title to be searched in lowercase, and trim function removes any whitespace for easier comparison.

Ember.js - Filtering all properties of a model

I am trying to filter all properties of a model by an input field in Ember.js. If the text field input is found in one of the models properties, I want to return the filtered results.
I already have a working solution, but i wanted to know if there is a better way to filter all properties, instead of getting them one after another. I already did a lot of research, but I could not find any better way to solve this problem. Here is the relevant code:
Model:
[
{
"source": "this is a source",
"title": "this is a title",
"message":"this is a message"
},
{
"source": "this is a source too",
"title": "this is a title too",
"message":"this is a message too"
}
]
Filter:
export default Ember.Component.extend({
filterText: "", //Input field value
filteredArticles: Ember.computed('filterText', function () {
var filter = this.get('filterText').toLowerCase();
return this.get('model').filter(function (item) {
return item.get('title').toLowerCase().indexOf(filter) !== -1 ||
item.get('message').toLowerCase().indexOf(filter) !== -1 ||
item.get('source').toLowerCase().indexOf(filter) !== -1
});
})
});
So is there a way to get all properties with one command (e.g. like item.get('allProperties'))?
In all Ember Object getProperties method is available.
If this is not an Ember Object, then you can use Ember.getProperties
But again those method return object with specified properties, not the values alone you are looking for. So your approach is correct, only if you are dealing with two or three properties in model object. if you think you will get more properties or dynamically you will add more properties to model object then you can do object iteration inside filter call back.
filterdText: Ember.computed('filterText',function(){
var filter = this.get('filterText').toLowerCase();
return this.get('model').filter((item,index) =>{
for(var key in item){
if( item.hasOwnProperty(key)){
if(item[key].toLowerCase().indexOf(filter) !== -1){
return true
}
}
}
return false;
})
})

jQuery see if key existing in entire JSON

I've got some JSON data in which I'm trying to check if a key is contained in the entire array and add a class or do something else. If there is one key contained in the array I want to perform an action otherwise if there is no key do something. I've been banging my head for hours ,inArray doesn't seem to be working for me or hasOwnProperty. I've got to be doing something stupid simple wrong here. Kind of a newb so please include code samples were applicable.
JS Fiddle: http://jsfiddle.net/AtC4G/
var data={"users":[
{
"firstName":"Ray",
"lastName":"Villalobos",
"userName":"rvilla",
"joined": {
"month":"January",
"day":12,
"year":2012
}
},
{
"firstName":"John",
"lastName":"Jones",
"joined": {
"month":"April",
"day":28,
"year":2010
}
},
{
"firstName":"John",
"lastName":"Johnson",
"userName": "jjoe"
}
]}
if($.inArray('userName', data.users) == -1) { alert('not in array'); }
if(data.users.hasOwnProperty('userName')){
alert('do something');
}
The [ indicates an array, so you need to treat it as an array (data.users[0], not just data.users):
if($.inArray('userName', data.users[0]) == -1) { alert('not in array'); }
if(data.users[0].hasOwnProperty('userName')){
alert('do something');
}
you can compare a variable with a undefined value
for(user_index in data.users){
user=data['users'][user_index];
if(user.userName==undefined){
alert('username undefined in user '+user.firstName+' '+user.lastName);
}
}
To find out, whether a property is set, I would go for a native JS.solution:
function containsKey(key){ return function(el){
return el[key]!==undefined;
}};
containsUserName=containsKey("userName");
console.log(data.users.some(containsUserName))
This is all you need.
containsKey is a closure, which saves the key, for which you are looking for.
containsUsername is the function, which is used to look for a specific property.
Read the MDN documentation of Array.some() for compatibility etc.
Here is a Fiddle to play with.
If you want to extract that element: Array.filter() might be of interest.

Javascript populate form after validation

I am doing a form for my javascript class, and I am getting stuck on a certain portion of it. I have a separate validator javascript file and call the function on the html file. All the validation works if the form areas are not filled in. What I want to do is if the fields are left blank they will fail the validation and will insert a value into that field. Below are an example of the form field, javascript function in the html page, and the external validator js file.
call function in html head:
function formvalidation(thisform) {
with (thisform) {
if (textbox_validation(first_name,"Please enter your first name.")==false)
{first_name.blur(); return false;};
if (textbox_validation(business_name,"Please enter your business. Please enter N/A if
you do not have one.")==false) { business_name.focus(); return false;
business_name.value=="N/A";};
The external js validator:
function textbox_validation(entered, alertbox) {
with (entered) {
if (value==null || value=="") {
alert(alertbox);
return false;
}
else {
return true;
}
}
}
So the validator works and focuses on the empty fields, but for some of my fields I want them to fill themselves with a certain value if validation fails or if it isnt filled int. The business_name line of code is when I tried to make it work. Any help is much appreciated!
Ordinarilly, you wouldn't use alert, but would instead put error messages in a span or div either near the input or at the top (or bottom) of the form. Additionally (as mentioned by #Frits van Campen) it is generally bad practice to use with
Try something like this instead:
function textbox_validation(entered, errormsg) {
var errbox = document.getElementById(entered.id + '-errors'); // just to prevent writing it twice
// Note this requires the input to have an id, and the errer box's id to be the same with an '-errors' suffix.
// Instead of using with, just acces properties normally
if (!entered.value) { // The `!` "neggation" operater makes "falsy" values `true`
// "falsy" values include `false`, the empty string, `0`, `null`, `undefined`, `NaN` and a few others
// Put the error message in the DOM instead of alerting it
errbox.innerHTML = errormsg;
return false;
}
else {
// Wipe any previous error messages
errbox.innerHTML = '';
return true;
}
}
And for the form validator, again; let's not use with. But also, when attempting to assing "N/A" to the value, you've used the comparison operator instead of the assignment operator, and you've done it after returning:
function formvalidation(thisform) {
// just use the `!` "negation" operator
if (!textbox_validation(thisform.first_name,
"Please enter your first name."))
{
thisform.first_name.blur();
return false;
}
if (!textbox_validation(business_name,
"Please enter your business. Please enter N/A if you do not have one."))
{
thisform.business_name.focus();
thisform.business_name.value = "N/A"; // for assignment, use `=`. `==` and `===` are used for comparison
return false; // a return statement ends the function, make sure it's after anything you want to execute!
}
}
Use the DOM to set the placeholder for the fields. Like this.
var myInput = document.getElementById('input1');
myInput.placeholder = 'This validation has failed.';

Script debugger confirms intended conditional check between JSON key and string, however I am getting an undesired result?

I am looking to modify the output table I am getting from this handy Json-to-HTML-Table script I stumbled upon here on SO. There is a point (line 86) where json-to-table.js passes a JSON object and generates array keys to be used as table headers. Optionally, this array_key function can generate only one key for a specified search_value parameter passed. I however [attempted] to modify it so that ALL array keys that did NOT match the search_value would be returned. Here is the function after my changes:
function array_keys(input, search_value, argStrict)
{
var search = typeof search_value !== 'undefined', tmp_arr = [], strict = !!argStrict, include = '', key = '';
if (input && typeof input === 'object' && input.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array
return input.keys(search_value, argStrict);
}
for (key in input)
{
if (input.hasOwnProperty(key))
{
include = false;
if (search)
{
if (strict && input[key] == search_value)
include = false;
else if (input[key] == search_value)
include = false;
else
include = true;
}
if (include)
tmp_arr[tmp_arr.length] = key;
}
}
return tmp_arr;
}
Now, the reason I did this is because I want my generated table to not include a specific column from my JSON object:
{
"examItemCategories": [
{
"catgoryName": "01-Normal processes",
"catgoryPath": "General Area\\01-Normal processes",
"numberOfItems": 2,
"percentage": "6.06"
}
]
}
Given that I can not modify the original JSON obj passed, I was determining whether or not to attempt to modify the table post creation (e.g. remove column), or during. After looking at the array_keys function, I felt I could easily invert the conditional checking for the search_value.
I now call array_keys(parsedJson[0], 'catgoryPath'); from json-to-table script. (Yes, catgoryPath is the correctly spelled name haha). Then I set a break point at the for loop within array_keys function to follow it through in Firebug.
First iteration: catgoryName is added to tmp_arr, 2nd iteration: catgoryPath is added to tmp_arr...and continues through 3rd and 4th iterations. I do not wantcatgoryPath added.
Looking at script debugger, on the 2nd iteration, whether or not catgoryPath gets added comes down to the conditional: else if (input[key] == search_value) line. The thing is, on the respective iteration both key and search_value variables equal "catgoryPath" according to Firebug. So therefore, include = false; should fire correct?
Any help is appreciated, apologies for the length and liberal usage of inline code.
Instead of using the array_keys function from the json-to-table script, if you are using JS > 1.8.5 you can use Object.keys(obj) to return an array of a given object's own enumerable properties.
The returned array of keys are then used as table headers under which the table populates with JSON data thanks to the script. Prior to the creation of table, I took my array of table headers and used array.splice(index, howMany) instead of delete (see here) to preserve my array index values.

Categories

Resources