astock Posted February 3, 2022 Share Posted February 3, 2022 Hello everyone, is there a way to preset a field in the backend with the value of the last entry? An example: A start and end mileage is entered in a logbook. For a new trip, the end mileage of the last trip should become the start mileage of the new trip. I can't find a way to show the value in the template. Is it possible with a hook? Link to comment Share on other sites More sharing options...
iank Posted February 3, 2022 Share Posted February 3, 2022 Yes, I think a hook would be needed. Something like this should give you a start, added to site/ready.php: $wire->addHookBefore("ProcessPageEdit::buildForm", function (HookEvent $event) { $page = $event->object->getPage(); $myTemplate = "logbook"; //or whatever your template is called if ($page->template != $myTemplate) return; if ($page->startMileage) return; //not if the start Mileage is present $prevPage = wire('pages')->get("template=$myTemplate,endMileage!=,sort=-created"); //get the most recent logbook with an endMileage value if ($prevPage->id) { $page->startMileage = $prevPage->endMileage; } }); 2 Link to comment Share on other sites More sharing options...
astock Posted February 5, 2022 Author Share Posted February 5, 2022 Hi iank, sorry for my late reply and thanks for your effort! I entered the code and it gives me a value - unfortunately from the wrong vehicle. It should depend on the previously selected car wich is the parent template. At the moment it brings me the value of each vehicle. Link to comment Share on other sites More sharing options...
iank Posted February 7, 2022 Share Posted February 7, 2022 Hi @astock, No problem. You just need to check for the new page's parent in the selector, something like this: $wire->addHookBefore("ProcessPageEdit::buildForm", function (HookEvent $event) { $page = $event->object->getPage(); $myTemplate = "logbook"; //or whatever your template is called if ($page->template != $myTemplate) return; if ($page->startMileage) return; //not if the start Mileage is present $parent = $page->parent; //get the current page's parent //get the most recent logbook with an endMileage value for the current parent $prevPage = wire('pages')->get("template=$myTemplate,endMileage!=,parent=$parent,sort=-created"); if ($prevPage->id) { $page->startMileage = $prevPage->endMileage; } }); 1 Link to comment Share on other sites More sharing options...
astock Posted February 7, 2022 Author Share Posted February 7, 2022 Hi @iank, wow, it works great! Thank you for your help and solving the problem. Link to comment Share on other sites More sharing options...
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