Jump to content
Torsten Baldes

Set InputField unrequired via hook

Recommended Posts

Hi,

I have a website with some users and admins who create and administrate these users. In their user profile is a checkbox which is set to required.

When the admins create or edit an user they have to check this checkbox to be able to publish this user. But this checkbox should only be checked by the user itself.

So I want to set this checkbox to "unrequired" when a user with a certain role is editing this profile. I tried to do this with the following hook (check for role not yet included), but I can't get it to work.

 

wire()->addHookBefore('InputfieldCheckbox::render', function (HookEvent $event) {
    if ($event->object->name != 'consent') return;

    $field = $event->object;

	$field->required = false;
	$field->set('required', 0);

});

 

It catches the right field but it doesn't set the field to unrequired.

Is this hook too late in the chain or do I have to do this with another property or method?

 

Thanks!

Share this post


Link to post
Share on other sites

Hi Torsden,

try to use ProcessPageEdit::buildForm, do a google search for this exact phrase and see if you can get examples. Sorry, on mobile 🙂

The principle is to get the right field in the hook and then just change the "required" setting.

  • Like 3

Share this post


Link to post
Share on other sites
20 hours ago, bernhard said:

Hi Torsden,

try to use ProcessPageEdit::buildForm, do a google search for this exact phrase and see if you can get examples. Sorry, on mobile 🙂

The principle is to get the right field in the hook and then just change the "required" setting.

 

Hi bernhart ;-),

thanks, that did the trick!

Here's my code, if someone also needs to do this:

wire()->addHookAfter('ProcessPageEdit::buildForm', function (HookEvent $e) {
	// skip the whole thing and return, if the user has not the proper role
	if (!wire('user')->hasRole('superuser') && !wire('user')->hasRole('useradmin')) return;

	$form = $e->return;
	$boxes = ['privacy', 'consent'];

	foreach ($boxes as $box) {
		$boxfield = $form->getChildByName($box);
		if($boxfield){
			$boxfield->required = false;
		}
	}
});

 

 

  • Like 3

Share this post


Link to post
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

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...