Jump to content

How can I prevent the name field being changed after a page is created?


DrQuincy
 Share

Recommended Posts

Just that…once a page is created I do not want to allow the page slug/name to ever be changed. So the name should be available no the initial page during creation but not after that.

Is that easy enough to do?

Thanks!

Link to comment
Share on other sites

Yes, quite easy ? 

$wire->addHookAfter(
  'ProcessPageEdit::buildForm',
  function (HookEvent $event) {
    $form = $event->return;
    $page = $event->process->getPage();

    // if page is young enough don't lock the page name field
    $lockPagenameAfterSeconds = 60;
    if ($page->created > time() - $lockPagenameAfterSeconds) return;

    // get field and set status to collapsed + locked
    $field = $form->get('_pw_page_name');
    $field->collapsed = Inputfield::collapsedLocked;
    $field->notes = 'Can not be changed any more';
  }
);

Alternatively you could use $page->meta() to set a flag at some point instead of waiting 60s.

  • Like 4
Link to comment
Share on other sites

I could have sworn there was a $config->advanced option in template settings to disable this, but apparently there is only one to prevent a page from being moved. Of course, you might want to do that, too, if you need stable urls.

Also note Bernhard’s hook only hides the field from the edit form, but it could still be changed through code or even (I believe) with simple browser dev tools trickery on the part of an editor. To prevent it even through the API you could probably hook into Pages::savePageOrFieldReady: https://processwire.com/api/ref/pages/save-page-or-field-ready/

  • Like 2
Link to comment
Share on other sites

3 hours ago, bernhard said:
// if page is young enough don't lock the page name field

I would just use if ($page->isNew()). This is true when we are on the very first page form with only the title and name fields. Then it's false.

This is the same as if (!$page->id).

Edited by da²
  • 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

  • Recently Browsing   0 members

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