Cookies help us deliver our services.

By using our services, you agree to our use of cookies. Learn more

I understand

Anyone who has ever developed a web application, has found himself dealing with the classic problem of the linked combos: by selecting a value from the first combo, the values of the second combo are filtered (or loaded).

An example? Nation and region, rather than region and city; or maybe the triad nation, region and city.

Fortunately, Liferay staff had the same problem and solved it by creating a very useful Javascript component: DynamicSelect.

In this first part of the article we will see a classic and simple use of the component, leaving to the second part a more complex case applied to custom entities.

Let's see the code in action and try to figure it out:

<%@ taglib uri="" prefix="portlet" %>
<%@ taglib uri="" prefix="aui" %>

<aui:select label="country" name="countryId" required="true" />
<aui:select label="region" name="regionId" required="true" />

<aui:script use="liferay-dynamic-select">
new Liferay.DynamicSelect([
		select: '<portlet:namespace />countryId',
		selectData: Liferay.Address.getCountries,
		selectDesc: 'nameCurrentValue',
		selectSort: true,
		selectId: 'countryId',
		selectVal: '8'
		select: '<portlet:namespace />regionId',
		selectData: Liferay.Address.getRegions,
		selectDesc: 'name',
		selectSort: true,
		selectId: 'regionId',
		selectVal: '8015'

Let's omit the taglibs inclusion because it's trivial and let's see the 2 combos, country and region, strictly empty; no matter where they are displayed on screen, the important thing is to decide the order in which they should be used, first the country and then the region.

Then we define the Javascript code, instantiating the Liferay.DynamicSelect component; the only required argument is a JSON objects array representing the combos in the exact order they are to be used. Each of these objects must have the following fields:

  • select, is the name of the combo (beware of the namespace);
  • selectData, is the Javascript function which is invoked to fill the combo;
  • selectDesc, is the field's name (from the single object returned by selectData) to use as the label of the combo's options;
  • selectSort, is a boolean flag to sort the combo's options;
  • selectId is the field's name (from the single object returned by selectData) to use as the value of the combo's options;
  • selectVal, is the value to preset the combo (in the example above, 8 is Italy and 8015 is Bologna).

Ok, but what exactly are Liferay.Address.getCountries and Liferay.Address.getRegions?

They are portal Javascript functions which, using the DWR mechanism, make an Ajax call to retrieve all the required data; they are defined inside the /html/js/liferay/address.js file. For the moment we don't go into further details, but I recommend you to have a look.

That's all! See you soon with the second part!