IN CQ, how to set value of all the items in Panel to blank - javascript

In ExtJS panel I need to set value of all items (e.g. textfield, pathfield) to blank. I don't want to set value of each individual item to blank but of whole panel in one go.
I am able to get list of items
function getAllChildren (panel) {
/*Get children of passed panel or an empty array if it doesn't have thems.*/
var children = panel.items ? panel.items.items : [];
/*For each child get their children and concatenate to result.*/
CQ.Ext.each(children, function (child) {
children = children.concat(getAllChildren(child));
});
return children;
}
but how to set to blank for whole panel? Please suggest what need to be done in this case.

Actually, it's not possible to do it with one liner - all at the same time. What your method returns is purely an array of objects. In fact if such syntax existed, it would iterate over all fields anyway.
Though clearing all fields, having the method you've proposed is very trivial to do. Just iterate over them all and call reset method. Mind some (especially custom) widgets might not handle it.
var fields = getAllChildren(panel);
CQ.Ext.each(fields, function(field) {
if (child.reset) {
child.reset();
}
});
You've got similar loop in your getAllChildren code - you might reset field at the same place.
The method is defined in Field type which is usually a supertype of each dialog widget. You can read more here.

Related

Is My Approach to the Todo App Delete Function Wrong?

I am learning React and just created a simple todo app using only React. My todo app has the standard structure of having a text input and an "ADD" button next to it. The user would type their todo in the input and every time they click on the "ADD" button next to it, a new ordered list of their inputs would appear underneath the input and "ADD" button.
The user can also delete a todo entry by clicking on the entries individually, like this:
To accomplish this behaviour of deleting entries, I used this delete function:
delete(elem) {
for (var i = 0; i < this.state.listArray.length; i++) {
if (this.state.listArray[i] === elem) {
this.state.listArray.splice(i, 1);
this.setState({
listArray: this.state.listArray
});
break;
}
}
}
My todo app works exactly the way that I want it to work, but as I look at other people's more conventional approach to this delete function, they either just simply use the splice method or the filter method.
For the splice method approach, they apparently just simply "remove" the unwanted entry from the listArray when the user clicks the particular entry. This does not work for me as using this method results in all my entries getting deleted except for the entry that I clicked on, which is the one that I want to delete.
On the other hand, the filter method approach apparently works by comparing the elem, which is the data passed from a child component, with each element in the listArray, and if the element in the for loop does not equal to the elem, then it would be passed onto a new array. This new array would be the one to not be deleted. This approach works better than the simple splice approach, however, one problem that I had encountered with this approach is that if I have more than one entry of the same value, for example, "Feed the dog". I only want one of the "Feed the dog" entries to be deleted, but it deletes both of them.
I thought of an approach to tackle this problem, eventually coming up with the current version of my code, which uses the splice method, but the splice method is used before I set it in the state. As evident here:
this.state.listArray.splice(i, 1);
this.setState({
listArray: this.state.listArray
});
My question can be broken down into three subquestions:
Considering that React states should be immutable, is the first line of the code above mutating my state? Is this approach not okay?
I thought that all React states were only possible to be changed inside a "setState" function, but my first line of code from above is not inside a setState function, yet it changed the state of listArray. How is this possible?
If my approach is mutating the state and is not ideal, how would you go about making the delete function so that it only deletes one entry and not more than one if there are multiple similar entries?
Yes, splice affects the array it acts on so don't use in this way. Instead you need to create a new array of the correct elements:
this.setState({
listArray: this.state.listArray.filter((el, idx) => idx !== i);
});
If you want to remove only the first instance, maybe couple with a findIndex (although indexOf would work in your example as well) first:
delete(elem) {
const idxToFilter = this.state.listArray.findIndex(el => el === elem);
if (idxToFilter < 0) {
return;
}
this.setState({
listArray: this.state.listArray.filter((el, idx) => idx !== idxToFilter);
});
}
This creates a new array without modifying the old which will cause anything that reacts to listArray changing to be notified since the reference has changed.

Issue Where Array is Limited to One Item At Any Given Time

I am running into an issue in a rather simple function that builds an array - and I'm drawing a blank on what the issue is. It's likely something simple - but I'm just not seeing it.
Here's the function:
private onSelection(selection)
{
if (selection)
{
const selectionsArray = [];
selectionsArray.push(selection);
console.log(selectionsArray);
console.log(selectionsArray.length);
return selectionsArray;
}
}
And the "selection" is being passed via a checkbox, like so:
<md-checkbox (click)="onSelection('A')">A</md-checkbox>
<md-checkbox (click)="onSelection('B')">B</md-checkbox>
<md-checkbox (click)="onSelection('C')">C</md-checkbox>
Right now regardless of what's clicked on in the checkboxes, my array is always just one item, and this is confirmed when I console out the length - which is always 1. What am I missing here? Why won't the array build into 2 and 3 items as multiple selections are pushed?
Your onSelection handler always reset the existing array before adding
the selected element. so you need to initialize your array outside of
your onSelection function.
suggestion:-
you can remove the if (selection) condition cause in your existing code, it'll always be true but you should check if a selected element is already in your selectionsArray before adding and in this way you won't get any duplicate entry in your selectionsArray. btw you should remove the const declaration of your selectionsArray, it doesn't make any sense.
const selectionsArray = [];
private onSelection(selection)
{
if (selection)
{
selectionsArray.push(selection);
console.log(selectionsArray);
console.log(selectionsArray.length);
return selectionsArray;
}
}

How to get checkbox value from localStorage

There is a page with a lot of different checkbox questions which then get submitted and populate the next page, this page however gets refreshed and the already annoyed potential client needs to go back and fill out the form again.
Now I have localstorage set up so he doesn't need to reselect all the checkbox again, he just needs to resubmit the form and his back in action.
How does one keep the values populated on the problem page so this fella doesn't have to go back to resubmit?
//SIZE SAVE
function save() {
localStorage.setItem('100', checkbox.checked);
var checkbox = document.getElementById('100');
localStorage.setItem('200', checkbox.checked);
var checkbox = document.getElementById('200');
//SIZE LOAD
function load() {
var checked = JSON.parse(localStorage.getItem('100'));
document.getElementById("100").checked = checked;
var checked = JSON.parse(localStorage.getItem('200'));
document.getElementById("200").checked = checked;
//THIS PAGE NEEDS THE CHECKMARK
echo get_site_url().
"/the/checkmark/selected/was/".$_POST['check_group'].
"/.png";
}
I think is much simple for now and especially for the feature if you write some code to make the management for all checkboxes form your form.
First of all it will be best if you group all your checkboxes into a single place.
Into a function like this you can declare all your checkbox selectors you want to save into the localStoarge (now you don't need to make variables for each selector into multiple places into your code)
function getCheckboxItems() {
return ['100', '200']
.map(function(selector) {
return {
selector: selector,
element: document.getElementById(selector)
}`enter code here`
});
}
Then to make things much simpler you can store all the values from the checkbox into a single object instead of save the result in multiple keys, in this way is much simpler to make management (let's say you want to erase all values or to update only a part)
The following function will take as argument all checkbox items from the function above, the point is the function above will return an array with the checkbox id and the checkbox element, than you just reduce all that array into this function into an single object containing all the ids and values, after this you just store the object into the localStorage
function serializeCheckboxes(elements) {
var container = elements.reduce(function (accumulator, item) {
accumulator[item.selector] = item.element.checked;
return accumulator;
}, {})
localStorage.setItem('container', JSON.stringify(container));
}
function save() {
var elements = getCheckboxItems();
serializeCheckboxes(elements);
}
After this you need another function who will read all the values from the localStorge and place them into your checkbox "checked" state
function readCheckboxes() {
var storage = localStorage.getItem('container'), //Your key
container = (storage) ? JSON.parse(storage) : {};
Object.keys(container).forEach(function(key) {
var element = document.getElementById(key);
if(element) {
element.checked = container[key];
}
});
}
This is just a simple service who can manage your problem but I think, for any additional changes you can customize this solution much simpler instead of keeping all into multiple variables, also if you add more checkbox elements into your application with this solution you just add the corresponding id into the array from the first function.
A live example here:
https://jsbin.com/xejibihiso/edit?html,js,output
localStorage has two main functions, getItem and setItem. For setItem you pass in a key and a value. If you write to that key again, it will rewrite that value. So in your case, if a box is checked you would do
localStorage.setItem("checkbox_value", true)
and when it is unchecked you would pass in false instead. To get the value you can look at using jQuery like so:
$(checkbox).is(':checked')
and use a simple if-else clause to pass in true or false. then when you reload your page, on $(document).ready() you can get the values using
localStorage.getItem(key)
and use JavaScript to set the check boxes values.
localStorage only allows you to store strings. What you can do is use a loop to create a string that has all the check boxes values separated by some delimiter. So, for example, if there are four check boxes with values true false false true your string would be "true\nfalse\nfalse\ntrue" where \n is the delimiter. then you can store that string in localStorage and when you retrieve it you can put all the values into an array like so:
array = localStorage.getItem(key).split('\n').
Then you can populate your check boxes with that newly retrieved array. Ask if anything needs clarification.

knockout js, add new item to an array

So this follows on from my previous question:
knockout js, add additional elements to an array
Basically I have an app where a user fills in certain data, clicks next and this is added to an array. However, what I'd like to do is add some items into the array before the user even begins using the app (these items I get from a database). The idea being that at the start they can view each item in the array and then choose and an item and edit this item. I've got a feeling I'm missing something blindingly obvious but I cannot seem to figure it out
Knockout observable arrays have equivalent functions to native JavaScript arrays. See: http://knockoutjs.com/documentation/observableArrays.html
So you need just to use arr.pop(item) or arr.push(item).
In case you need to replace all items and want to avoid multiple events to raise, use observableArray.valueWillMutate() and valueHasMutated() functions. See sample where I do swap the entire array:
ko.observableArray.fn.replaceWith = function (valuesToPush) {
// NOTE: base on - ko.observableArray.fn.pushAll
var underlyingArray = this();
var oldItemcount = underlyingArray.length;
this.valueWillMutate();
// adding new items to obs. array
ko.utils.arrayPushAll(underlyingArray, valuesToPush);
// removing old items (using KO observablearray fnc.)
if (oldItemcount > 0)
this.removeAll(underlyingArray.slice(0, oldItemcount));
this.valueHasMutated();
return this; //optional
};

Kendo UI - Property Changed MVVM

I seem to be having issues databinding 'calculated' fields with Kendo UI.
I am attempting to do data-binding with several what I will call 'calculated' fields. I have a grid, several buttons, filters and some sorting on a page that are all using the same datasource, an observable array called 'allItems'. allItems is populated via a service call and sorted, manipulated and otherwise changed while the user is on the page via buttons.
There are several navigational buttons and several div's that are populated based on information in the previous item, current item and next item in accordance to the current filters and sorts applied. Those buttons contain information in them that is extracted from the previous, current and next items as they related to the allItems list (ie the objects are actually held in the allItems array and are in fact observable objects).
so in the viewmodel object I have something like this (please excuse short handing):
var viewmodel = kendo.observable({
var allItems = observablearray[]
var currentIndex = 1; //or other default value
var changeCurrentItem = function(){
var self = this;
//do some stuff
//stuff might include modification to allItems
self.set("currentIndex", someNewValue);
}
var previousItem = function(){
return self.get('allItems')[currentIndex - 1];
}
var currentItem = function(){
return self.get('allItems')[currentIndex];
}
var nextItem = function(){
return self.get('allItems')[currentIndex + 1];
});
return viewmodel;
The buttons and other info boxes are bound to previous,current and next Items. But this does not appear to work. I've had to make previous, current and nextItems copies of what lives in the allItems array and update those 3 objects at the same time. Not that big of a deal, but I just would like to, you know, not store copies of objects if I don't have to. I was hoping there might be a NotifyPropertyChanged("MyProperty") similiar to C#/Xaml that I missed while going through the API. This sort of functionality will be most useful to me for future tasks I have on my list due to some of the complexities of our calculated fields and the need to reducing memory consumption as devices get smaller.
Thanks for any help,
~David
Whenever a property of the view model changes, the change event is triggered.
To make this work in calculated fields, you need to access the relevant fields using ObservableObject.get(). See this section in the documentation.
2 possible problems.
1) How do you get items into allitems?
2) You should also .get("currentIndex") since that is the value that you update in changeCurrentItem
var currentItem = function(){
return self.get('allItems')[self.get('currentIndex')];
}
That should cause viewModel to fire its change event for thecurrentItem calculated field whenever allItems or currentIndex changes.
If all else fails, you can manually fire the change event by doing:
viewmodel.trigger("change", { field: "currentItem" });
viewmodel.trigger("change", { field: "previousItem" });
viewmodel.trigger("change", { field: "nextItem" });
which would be similar to calling NotifyPropertyChanged("currentItem") in XAML.

Categories