How to make an optional initRefSelect

4.0
How to make an optional initRefSelect
0
Tags: #<Tag:0x00007fcf151642e8>

(scampano) #1

The initRefSelect object hooks allows for manadatory object filtering when you are selecting a referenced object (1/N relation):

@Override
public void initRefSelect(ObjectDB parent) {
	if(parent!=null && parent.getName().equals("ParentObject")){
		setFieldFilter("fieldToFilter", parent.getFieldValue("parentFieldToFilterOn"));
	}	
}

A limitation to that is that it is then impossible to allow the user to remove the filter (that’s because the initRefSelect filter is called before each search, and removing a filter is in fact doing a new search).

The trick is to set a parameter in the parent (for example in the initUpdate hook), so that you can test it the initRefSelect and only set the field filter once.

In the parent object:

@Override
public void initUpdate(){			
	HashMap<String, String> filters = new HashMap<>();
	filters.put("parentFieldToFilterOn", getFieldValue("parentFieldToFilterOn"));
	filters.put("etc", getFieldValue("etc"));
	getGrant().setParameter("PARENT_FILTERS", filters);
}

In the referenced object:

@Override
public void preSearch(){		
	if(getInstanceName().equals("ref_ajax_ReferencedObject") && getGrant().hasParameter("PARENT_FILTERS")){
		HashMap<String, String> filters = (HashMap<String, String>) getGrant().getObjectParameter("PARENT_FILTERS");			
		setFieldFilter("fieldToFilter", filters.get("parentFieldToFilterOn"));
		setFieldFilter("etc", filters.get("etc"));
		getGrant().removeParameter("PARENT_FILTERS");
	}
}