Jump to content

Change field "Only visible if..." through API


iipa
 Share

Recommended Posts

Hi!

I have two Page Reference fields: Category and Subcategory. Category is parent of Subcategory, and can have 0 to n Subcategories. Fields are selected by dropdown selection.

I'm trying to achieve following logic:

1. Select Category (obviously works)

2. Change Subcategory options based on selected Category (this works)

3. Hide the Subcategory field if Category has no Subcategories (to prevent weird dropdown with nothing to select)

I have tried to investigate two possible alternatives to achieve step 3:

A) Make dynamic condition into Subcategory selection's "Only visible if..." field

B) Make a hook that fires when Category changes, then hides Subcategory field if Category has no children

So far I haven't been successful in either. Conditions I've tried always lead to hidden field, and I haven't been able to find set up a hook that fires on field change.

So here's the question (finally): Is there a way to alter field visibility in API, for example in ready.php or inside a hook? In API I could loop through categories, find the ones that have children and then make a selector based on their IDs.

Link to comment
Share on other sites

9 hours ago, iipa said:

Is there a way to alter field visibility in API, for example in ready.php or inside a hook?

Here's an example...

The page structure:

2019-05-30_101406.png.94c9de895a96009038bf2485e47a512e.png

Some pet species have breed child pages and some do not.

The selector string for selectable pages for the breed field is "parent=page.species".

In ready.php:

$wire->addHookAfter('ProcessPageEdit::buildForm', function(HookEvent $event) {
	/* @var InputfieldForm $form */
	$form = $event->return;
	$breed_field = $form->getChildByName('breed');
	if(!$breed_field) return;
	$species_with_breeds = $event->wire('pages')->find('parent=/selects/pets/, children.count>0');
	$breed_field->showIf = 'species=' . $species_with_breeds->implode('|', 'id');
});

selects.gif.4ef74f092352650d806db8db39b15288.gif

  • Like 5
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...