Home
NexoPOS

Conditional Field Refresh

From NexoPOS 5.3.x, certain fields such as "select", "multiselect" and "search-select" will be subject to conditionally refresh their options based on their siblings' values.

The idea here is to always give accurate choices to the user based on a previous choice he has made. Let's consider you have a form that has 2 select fields. The first select field lists all countries, and the second select field lists towns in the country. It will make more sense if the second select field options are updated to match the country selected in the first field.

Settings Up Field

For a field to watch other fields change and update its options, you need to provide some extra options to the field from the backend side.

<?php
use App\Classes\FormInput;

// ...

$country = FormInput::searchSelect(
  label: __( 'Countries' ),
  name: 'country',
);

$town = FormInput::searchSelect(
  label: __( 'Town' ),
  name: 'town',
  refresh: FormInput::refreshConfig(
    url: '', // url to fetch new options
    watch: 'country', // the name of the field to watch changes
);

In the above example, the first field is "country" and the second is "town". On the second field, we'll provide the option "refresh", for which we'll use FormInput::refreshConfig. This function returns an array with "url" and "watch".

url: This is the URL to use to fetch the new options. Note that NexoPOS will perform a POST request to that URL with only the input "identifier", which is the value selected on the "watch" field (in our example, it's the country).

watch: This is the name of the field to watch. Upon any change that will be made in that field, all the fields that define a "refresh" property will be notified.

Returned Value

As NexoPOS requests the URL provided, that URL must return a valid response for it to work. The input that watch changes expect as a response is a list of options in an array. Make use of "Helper::toJsOptions" to convert a collection of models into a valid JavaScript array that NexoPOS can understand.

image770394

This is an example of output expected by NexoPOS.