Jump to content

Dynamic parent for creating new page with page reference field


bbb
 Share

Recommended Posts

I have 2 page reference fields; brand and model.

The brand field has an assigned template and parent so I'm able to create new pages from within the page with this field.

The model field is dependant om the value of brand with the following:

parent=page.brand

But I can't figure out how to assign a dynamic parent the model field so that I can add pages (models) under the correct brand.

whats the best way to go about this?

Link to comment
Share on other sites

$wire->addHookBefore('InputfieldPage::processInputAddPages', function($event) {
    $field = $event->object;
    $page = $field->hasPage;
    if($field->name == "model"){
		$brand = $page->brand;
		if($brand){
 			$dynamicParent = $page->brand;
    		$field->set("parent_id", $dynamicParent->id);
		}
	}
  
});

I think this should work! Let me know if it does ?

  • Like 4
Link to comment
Share on other sites

Thanks! got it partially working. Doesn't check the field value but the saved page value which isn't handy if you change brand field or the brand field is empty. But I think I can fix this ?

  • Like 1
Link to comment
Share on other sites

Doesn't it work like that straight out of the box like that? I'd think it would, from the logic leading to this setAttribute.

My first approach would be to try just that inside the hook:

$event->object->setAttribute('value', $newCreatedPage); 

But honestly haven't tried!

Link to comment
Share on other sites

Sorry, I wasn't clear, I meant, when you select a different brand than was already saved and add a new model at the same time, the hook won't work  because it's attempting to create a new page (model) under the old brand and not the newly selected brand. In other words, changing both brand and model at the same time breaks the hook.

  • Like 1
Link to comment
Share on other sites

Oh you are very right! I see that InputfieldPage has a $pagesAdded property that seems to be filled only when pages are added, WHAT IF, you check both fields for this property on a hook right before saving the page. This way you can see if a brand has been added in the request, and if any new created model also,  change its parent accordingly. 

 

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

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...