AndZyk Posted February 28, 2023 Posted February 28, 2023 Hello, a client wanted to have the option to activate/deactivate two buttons on a page. But the default behaviour should be that both buttons are activated. So I have added a select options field with two options, which control if the buttons are visible or not. Now I can set both options to be preselected, but in order to makes this work, the field has to be required. But I don't want this to be a required field, because pages also should have the option to show no buttons. I honestly don't understand what's the reason, why this field has to be required, in order to show preselected options. Now I could add a third option "No buttons" or flip the logic to use this field for hiding butttons or I could use a hook for preselecting the options. But I am not sure which hook to use. But I hope there is a more elegant solution. Had somebody else this case before? I think this should be a common case. Regards, Andreas
AndZyk Posted February 28, 2023 Author Posted February 28, 2023 I have figured out which hook suits my case and decided to pre-select the options with the pages added hook: // Hook after page added $this->addHookAfter('Pages::added', function(HookEvent $event) { $page = $event->arguments(0); if ($page->template->name === "job") { // Pre-select job buttons $page->setAndSave("jobButtons", [1, 2]); } }); But I find this solutions still not very satisfying, because I think it should be possible to pre-select options without having the field to be required. Unless there is a reason behind, that I am not able to see.
bernhard Posted February 28, 2023 Posted February 28, 2023 34 minutes ago, AndZyk said: But I find this solutions still not very satisfying, because I think it should be possible to pre-select options without having the field to be required. Unless there is a reason behind, that I am not able to see. I agree it's not the best UX, but have a read here: https://processwire.com/talk/topic/14979-why-is-a-value-required-to-pre-check-checkboxes/?do=findComment&comment=134243 I think that makes sense and your Pages::added hook seems to be a good solution as it's the only other possible option that ryan mentioned. PS: If you are using custom page classes you can make it a MagicPage and then it's simply this: public function onCreate() { $this->youroptions = [1, 2]; } 1
AndZyk Posted February 28, 2023 Author Posted February 28, 2023 Thank you @bernhard for pointing me to this thread. This explains why this behaviour is necessary, although I wish it wouldn't. ? Then I will stick to my hook solution, if this is a recommended solution for this case. So far I haven't used custom page classes, but thanks for the hint.
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now