...
3.5 Criteria modifier example
Single parameter example:
Code Block theme Eclipse language java linenumbers true
...
public void filterOutNotBelongingToCurrentUser(final SearchCriteriaBuilder scb) {
...
...
scb.add(SearchRestrictions.eq("owner", securityService.getCurrentUserName()));
...
}
- Context example:
Models:- Shop
- Chain
- Industry
- Shop hasMany Industries
- Chain hasMany Industries
- Shop belongsTo Chain
Target: In industires lookup in shop details view show only industires that are in relation with chain of the shop.
Code Block theme Eclipse language html/xml linenumbers true <view name="shopDetails" modelName="shop" ...> <component type="window" name="window"> ... <component type="form" name="form" reference="form"> ... <component type="lookup" name="industry" reference="industryLookup" field="industries" defaultVisible="false" persistent="false" hasLabel="false"> ... <criteriaModifier class="com.qcadoo.sdt.basic.criteriaModifiers.ShopIndustryLookupCriteriaModifier" method="restrictIndustriesToChainContext" /> </component> ... </component> </component> <hooks> <beforeRender class="com.qcadoo.sdt.basic.hooks.view.ShopDetailsBeforeRenderService" method="setCriteriaModifierParameters"/> </hooks> </view>
Code Block theme Eclipse language java linenumbers true @Service public class ShopDetailsBeforeRenderService { public void setCriteriaModifierParameters(final ViewDefinitionState state) { LookupComponent industryLookup = (LookupComponent) state.getComponentByReference("industryLookup"); FormComponent form = (FormComponent) state.getComponentByReference("form"); Entity shop = form.getEntity(); if (shop.getId() != null) { Entity chain = shop.getBelongsToField(ShopFields.CHAIN_FIELD); FilterValueHolder holder = industryLookup.getFilterValue(); holder.put(ShopIndustryLookupCriteriaModifier.CHAIN_PARAMETER, chain.getId()); industryLookup.setFilterValue(holder); } } }
Code Block theme Eclipse language java linenumbers true @Service public class ShopIndustryLookupCriteriaModifier { public static final String CHAIN_PARAMETER = "chain"; private static final String CHAIN_REQUIRED = "Chain parameter is required"; public void restrictIndustriesToChainContext(final SearchCriteriaBuilder scb, final FilterValueHolder filterValue){ if(!filterValue.has(CHAIN_PARAMETER)){ throw new IllegalArgumentException(CHAIN_REQUIRED); } Long chainId = filterValue.getLong(CHAIN_PARAMETER); scb.createAlias(IndustryFields.CHAINS_FIELD, "c").add(SearchRestrictions.eq("c.id", chainId)); } }