Jump to content

Preset a field in the backend


astock
 Share

Recommended Posts

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

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;
	}
});

 

  • Like 2
Link to comment
Share on other sites

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

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;
	}
});

 

  • Thanks 1
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...