Prevent selection of a particular item in spark list - flex4.5

I have a Spark List which has a custom itemRenderer for rendering each item in the List.
I wish to prevent an item in that list from being selected (based on some custom logic) by the user.
What is the best way I can achieve this?
Here's how my List is defined:
<s:List id="myList" itemRenderer="com.sample.MyItemRenderer" />
and of course, I have a item renderer defined as the class com.sample.MyItemRenderer.

The selection of items is handled by the list alone as far as I know, so I would say that you can manage it from there. I would have a field on the Objects that are in the list called "selectable" or something like that and when the list item is changing check to see if the new item is actually selectable and if it isn't then you can either have it clear the selection or reset to the previous selection. You can accomplish that by reacting to the "changing" event on the list component and calling "preventDefault" on the IndexChangeEvent as follows:
protected function myList_changingHandler(event:IndexChangeEvent):void {
var newItem:MyObject = myList.dataProvider.getItemAt(event.newIndex) as MyObject;
if(!newItem.selectable) {
event.preventDefault();
}
}
// Jumping ahead ...
<s:List id="myList" changing="myList_changingHandler(event)" // ... continue implementation
The relevant part of the MyObject class is as follows:
public class MyObject {
private var _selectable:Boolean;
public function MyObject(){
}
public function set selectable(value:Boolean):void {
_selectable = value;
}
public function get selectable():Boolean {
return _selectable;
}
}

Related

Unkown Key in Vaadin 14 Grid during selection

I'm using a Grid in Vaadin 14. The grid is in multi-selection mode.
The selection handler takes a couple of seconds to complete and I'm calling setItems(...) at the end to update the items in the grid.
When the user selects another row while the previous selection handler is still running, I get an "Unknown key" error similar to the one described in https://github.com/vaadin/vaadin-grid-flow/issues/322, even though the new set of items still contains the selected item (another object instance but same according to equals()). This seems to be because the keys in the KeyMapper have already been changed due to setItems(), so the key coming from the client is not present anymore.
Is there a way to work around this, for example by disabling selection while the previous request is in progress?
UPDATE
To work around this Vaadin bug, I'm also calling setPageSize() with the exact number of items as argument. But it seems the same problem occurs even if I don't call setPageSize(), so it's probably due to setItems().
Do not change the grids items inside a SelectionListener.
You can still do all the things you wanted, but setting the items anew is not actually needed. In fact it will only create problems as you are experiencing now.
While working at this answer, I realized you will need to do your own Checkbox Column in order to be able to do actions for the one item that was just "selected", instead of removing all then add all selected ones (because much better performance). Here is how that could look.
// in my code samples, a `Foo` item can have many `Bar` items. The grid is of type Bar.
Grid.Column customSelectionColumn = grid.addComponentColumn(item -> {
Checkbox isSelected = new Checkbox();
isSelected.setValue(someParentFoo.getBars().contains(item));
isSelected.addValueChangeListener(event -> {
boolean newSelectedValue = event.getValue();
if(newSelectedValue){
someParentFoo.getBars().add(item)
} else {
someParentFoo.getBars().remove(item);
}
fooRepository.save(someParentFoo);
});
});
// make a Checkbox that selects all in the header
Checkbox toggleSelectAll = new Checkbox();
toggleSelectAll.addValueChangeListener(event -> {
if(event.getValue()){
someParentFoo.getBars().addAll(allGridItems);
} else {
someParentFoo.getBars().removeAll(allGridItems);
}
fooRepository.save(someParentFoo);
grid.getDataProvider().refreshAll(); // updates custom checkbox value of each item
});
gridHeaderRow.getCell(customSelectionColumn).setComponent(toggleSelectAll);
I solved this problem. Vaadin use data as key in HashMap. You need calc hashCode use immutable data fields. For example
public class TestData {
private int id;
private String name;
public TestData(int id) {
this.id = id;
}
#Override
public int hashCode() {
return Objects.hash(id);
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

how to retain expand/collapse state in jqgrid grouping?

I have implemented a jqgrid in grouping method. By default I have kept the groups collapsed using groupCollapse:true parameter of jqgrid. My grid works well but When I expand the group and sort a column, the whole grid is reloaded and the expanded state of the column is not retained. How can I retain the expanded state while sorting?
Please write always which version of jqGrid, which you use (can use), and from which fork (free jqGrid, commercial Guriddo jqGrid JS or an old jqGrid in version <=4.7).
Your requirements could be easy realized in "free jqGrid", which I develop. It allows to use groupCollapse as callback function, which returns Boolean (see the issue). In combination with onClickGroup callback or jqGridGroupingClickGroup event one can easy persist the grouping state.
UPDATED: I created the demo https://jsfiddle.net/92da8xhq/, which demonstrates how one can persist the collapsing state in the grouping grid. Below I describe shortly the code. The demo uses one level of grouping to make the code more simple for understanding.
I added custom collapsedGroups: {} parameter to jqGrid. We will use the parameter to hold the list of collapsed groups. I used collapsedGroups: { "test2": true } in the demo to demonstrated that we can create the grid with some collapsed groups at the beginning. We don't use the value of the property of collapsedGroups object. Just the existence of the property test2 for example means that the group with the value test2 has collapsed state.
The demo uses groupCollapse property of groupingView defined as the callback function. The function tests whether the group is in the list of collapsed groups (has collapsedGroups property with some value)
groupingView: {
groupField: ["name"],
groupCollapse: function (options) {
var collapsedGroups = $(this).jqGrid("getGridParam", "collapsedGroups") || {};
// options looks like { group: number, rowid: string }
if (collapsedGroups.hasOwnProperty(options.group.value)) {
return true;
}
return false;
}
}
We adjust additionally the properties of the custom collapsedGroups parameter after expanding/collapsing of the group. We use the following onClickGroup callback:
onClickGroup: function (hid, isCollapsed) {
var p = $(this).jqGrid("getGridParam"),
iGroup = $(this).jqGrid("getGroupHeaderIndex", hid),
group = p.groupingView.groups[iGroup];
if (p.collapsedGroups == null) {
// be sure that the custom parameter is initialized as an empty object
p.collapsedGroups = {};
}
if (isCollapsed) {
// we place group.value in the p.collapsedGroups object as a property
if (!p.collapsedGroups.hasOwnProperty(group.value)) {
// create the property group.value in with some value
p.collapsedGroups[group.value] = true;
}
} else if (p.collapsedGroups.hasOwnProperty(group.value)) {
// remove group.value property from the p.collapsedGroups object
delete p.collapsedGroups[group.value];
}
}
groupingView: {
groupCollapse: true,
groupField: ["name"],
plusicon: 'ace-icon fa fa-plus-square purple',
minusicon: 'ace-icon fa fa-edit red'
}

MVVMCross ListView - how to populate only with the list items matches certain conditions?

MVVMCross ListView - How to display a list of items in a listview grouped by a status? For exampled activate or deactivated
I have added two listview to the layout and set the datasource to have two lists (activatedItems and deactivatedItems => both of them derived from ListOfItems. ) using the xaml data binding with now code behind. But had a problem in the data not updated when there is a change to the underlying list (ListOfItems).
To resolve this, I have to re create the UI by setting the content view whenever there a change to the data set.
This is not an elegant solution and I would like to have one listview with sections "Activated" and "Deactivated". Then on touching the Activated item should get added to the Deactivated list and the UI should reflect the same.
Since you have a LoginItemModel with a Title property (let's assume it's a string property), I would recommend you to extract this to an ILoginItemModel interface and also add a bool IsHeader property. This way:
public interface ILoginItemModel {
public bool IsHeader { get; }
public LoginSection ItemGroup { get; }
public string Title { get; }
}
Make your LoginItemModel extend this ILoginItemModel interface and make IsHeader always return false.
public bool IsHeader => false;
Write a second class extending this same interface, let's call it LoginItemHeaderModel. This class will just have these three properties:
public class LoginItemHeaderModel : ILoginItemModel {
public bool IsHeader => true;
LoginSection _itemGroup;
public LoginSection ItemGroup => _itemGroup;
string _title;
public string Title => _title;
public LoginItemHeaderModel(LoginSection itemGroup, string title) {
_itemGroup = itemGroup;
_title = title;
}
}
Now we have two models that fits into a single IList<ILoginItemModel>.
Back to your view model, you can declare a fourth list property and put it all together along with your new headers:
public List<ILoginItemModel> SectionedLoginItems {
get {
var values = Enum.GetValues(typeof(LoginSection)).Cast<LoginSection>();
List<ILoginItemModel> list = new List<ILoginItemModel>();
foreach (LoginSection loginSection : values) {
list.Add(new LoginItemHeaderModel(loginSection, loginSection.ToString()));
list.AddRange(LoginItems.Where(l => l.ItemGroup == loginSection));
}
return list;
}
}
Now you have your single sorted and with section headers list.
You should now write a new layout for those header items (aren't you going to make them look like the common items, right?) and, in your custom MvxAdapter, inside the GetBindableView method, check whether the object source (which will be an ILoginItemModel object) is a header item or not.
Whenever you make a change to ActiveLoginItems or DeactivatedLoginItems, make a call to RaisePropertyChanged in your ViewModel i.e.
RaisePropertyChanged(() => ActiveLoginItems);
or
RaisePropertyChanged(() => DeactivatedLoginItems);
That should make the MvxListView update with the changes.

Get changed unsaved property value of a node in content tab, after clicking save button and before saving the changes. Umbraco

Update:
I want to get a node's property value that has been changed after clicking save button and before saving the changes programmatically, on content tab in BackOffice.
The node could contain many properties. When the save button is clicked, I want to first get the new changed value for the node's properties. I think Umbraco should have APIs to get those in server side.
Any idea would be very much appreciated.
You want to wire into the Document.BeforeSave method in an IApplicationEventHandler class. Like so (assuming you're changing bodyText from "apple" to "orange"):
using umbraco.cms.businesslogic.web;
using Umbraco.Core;
using Umbraco.Web;
namespace ClassLibrary1
{
public class Class1 : IApplicationEventHandler
{
public void OnApplicationStarted(UmbracoApplication httpApplication, ApplicationContext applicationContext)
{
Document.BeforeSave += new Document.SaveEventHandler(Document_BeforeSave);
Document.AfterSave += new Document.SaveEventHandler(Document_AfterSave);
}
void Document_BeforeSave(Document sender, umbraco.cms.businesslogic.SaveEventArgs e)
{
// your code goes here!
sender.getProperty("bodyText").Value // returns apple
}
void Document_AfterSave(Document sender, umbraco.cms.businesslogic.SaveEventArgs e)
{
// your code goes here!
sender.getProperty("bodyText").Value // returns orange
}
public void OnApplicationStarting(UmbracoApplication httpApplication, ApplicationContext applicationContext)
{
// unused
}
public void OnApplicationInitialized(UmbracoApplication httpApplication, ApplicationContext applicationContext)
{
// unused
}
}
}
I tested this in Umbraco 4.11
Cheers
Jonathan
What you could do is use a jquery event handler, that is targeted at the field in the umbraco admin you want to check for changes. This example will work by finding the label of the umbraco field you want to monitor and then adding a jquery event handler that will fire when the field that is the sibling to the label is changed - this example will work for any changes to the 'Name' field that is on every node's 'properties' tab. Different field types will hold the value differently, so $(this).val() should usually work for most - but not all field types.
Drop this into the end of \umbraco\editcontent.aspx
<script type="text/javascript">
$(document).ready(function () {
$("div.propertyItemheader:contains('Name') + div.propertyItemContent").keyup(function () {
alert("field changed");
});
});
</script>

Nested bean : a collection inside an object

I got a simple POJO class that i wish to display / update in a form
Using the BeanItem class and the binding of component data, i was able to quickly display the first attributes of may data class. However i've hit a wall for tow related attributes :
my class posses a set of available status, as a list of object 'AppStatus'. it also possess a current status, that is one of the status in the 'available' list.
I would like to display the list in the form as a combobox, with the current status selected.
I'we managed to associate the 'available' attribute with a combobox, but i can't seem to be able to fill this combobox when setting the data source (method setItemDataSource). How do i get the avalaible status list and the current status from my Item ?
I could always use a workaround and add a parameter to the method to get the source objet in addition to the BeanItem, but i would prefer to avoid this if the Item properties can give me my attribute.
Regards
Edit : shortened exemple, with code from Eric R.
class Status {
String id;
Sting label
+ setter /getter
}
class App {
String AppId;
String AppLabel
ArrayList<Status> availablestatus;
Status currentStatus
+setter/getter
}
in the form extension, in the createField of the fieldfactory i added the following lines
if ("status".equals(propertyId)) {
// create the combobox
ComboBox status = new ComboBox(
texts.getString("application.label.status"));
status.setItemCaptionMode(AbstractSelect.ITEM_CAPTION_MODE_PROPERTY);
status.setItemCaptionPropertyId("label");
status.setImmediate(true);
status.setNullSelectionAllowed(false);
IndexedContainer container = new IndexedContainer(
(Collection<ApplicationStatus>) item.getItemProperty(
"availableStatus").getValue());
status.setContainerDataSource(container);
status.setPropertyDataSource(item.getItemProperty("currentStatus"));
return status;
} else...
this didn't work, i do get a combobox, with the correct number of lines, but all empties.
i tried to use a beanContainer instead of a IndexedContainer
BeanContainer<String, ApplicationStatus> container =
new BeanContainer<String, ApplicationStatus>(ApplicationStatus.class);
container.addAll((Collection<ApplicationStatus>) item
.getItemProperty("availableStatus").
container.setBeanIdProperty("id");
the result is slightly better, since i do have the available values in the combobox.
only the currentValue is not selected...
I also tried to use a nestedbean property to get the id of the currentstatus, but the result is still not valid... i get a combobox, with the correct value selected, but i can not see others values anymore, since the combobox is readonly ?(even with setReadOnly(false);)
I suggest my way to resolve this. I don't think this is the nicest way, but it's works.
The beanItem class contains all you need.
I did the following in a simple project and it's work verry well :
ComboBox status = new ComboBox("ComboBox");
status.setImmediate(true);
status.setNullSelectionAllowed(false);
for(Status st : (Collection<Status>)item.getItemProperty("availableStatus").getValue()) {
status.addItem(st);
status.setItemCaption(st, st.getLabel());
}
status.setPropertyDataSource(item.getItemProperty("currentStatus"));
Hope it's works.
Regards Éric
From the vaadin demo site you can get this sample that show how to fill a combobox with countries. You could do the same i would guess (not sure I understand your problem 100%):
myForm.setFormFieldFactory(new MyFormFieldFactory ());
private class MyFormFieldFactory extends DefaultFieldFactory {
final ComboBox countries = new ComboBox("Country");
public MyFormFieldFactory () {
countries.setWidth(COMMON_FIELD_WIDTH);
countries.setContainerDataSource(ExampleUtil.getISO3166Container());
countries
.setItemCaptionPropertyId(ExampleUtil.iso3166_PROPERTY_NAME);
countries.setItemIconPropertyId(ExampleUtil.iso3166_PROPERTY_FLAG);
countries.setFilteringMode(ComboBox.FILTERINGMODE_STARTSWITH);
}
#Override
public Field createField(Item item, Object propertyId,
Component uiContext) {
Field f = (Field)item;
if ("countryCode".equals(propertyId)) {
// filtering ComboBox w/ country names
return countries;
}
return f;
}
}

Resources