Jump to content

Diplaying since when a page is published


torf
 Share

Recommended Posts

I need to show (in my backend) since when a page special type of page has been published (not created, as there may be a long delay between creation and publishing). So I made a datefield in my template and added following code to my site\ready.php

$wire->addHookBefore('Page(template=templateName)::published', function($event){
	$page = $event->arguments(0);
	$this->message("the Hook has been called");
    if($page->hasField("myDateField")) {
        $newDate = date("d.m.Y");
        $page->myDateField = $newDate;
    }
});

But for some reason the hook is not called when I publish the page. Is there something I'm missing?

Link to comment
Share on other sites

The "published" hook is in the Pages class. So it should look something like this:

$wire->addHookBefore('Pages::published', function($event){
	$page = $event->arguments(0);
    if($page->template->name !== 'templateName')
        return;
	$this->message("the Hook has been called");
    if($page->hasField("myDateField")) {
        $newDate = date("d.m.Y");
        // Need to call "save" explicitely after publishing since saving is already done by then.
        // Wrapped it all in a single call, not changing modified user and timestamp again
        $page->setAndSave('myDateField', $newDate, ['quiet' => true]);
    }
});

You could consider hooking Pages::publishReady instead and set your myDateField there, that would save you the second write to the database.

  • Like 2
Link to comment
Share on other sites

@BitPoet Oh. I missed that little piece of Information. Thanks a lot. And you're right. I'll have a look into Pages::publishReady.

@bernhard and @Jan Romero I admit that it would be nicer without an extra field, but as there is the possibility that the date needs to be changed manually in the future I'd rather go with an additional field before I have to reinvent everything in five months.

Link to comment
Share on other sites

<?php
  public function editFormContent($form)
  {
    $form->add([
      'type' => 'text',
      'name' => 'published',
      'label' => 'Published at',
      'value' => date("Y-m-d H:i:s", $this->published),
    ]);
  }

  public function onProcessInput($form, $input)
  {
    $pub = date("Y-m-d H:i:s", strtotime($input->published));
    $query = $this->wire->database->prepare(
      "UPDATE pages SET published=:pub WHERE id=:id"
    );
    $query->execute([':pub' => $pub, ':id' => $this->id]);
  }

Ixt4AaX.png

? 

  • Like 2
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

×
×
  • Create New...