Jump to content

[SOLVED] Check if a field has a unique value across all pages (page editor)


Gadgetto
 Share

Recommended Posts

Hi there,

I'd like to prevent duplicate values in a specific page field (FieldtypeText) across all pages. The hook should also prevent saving of the page if a duplicate value is detected. Therefore I created two hook methods but I can't get it to work properly.

Here are both hooks placed in init() method of an autoloader module:

The first hook is to initially preset the field with the page id. The field value can be customized by the admin before saving.
The second hook should check if the value is unique.

If I create a new page and try to save, the WireException is already triggered in first step of page creation, where you enter the page title: SKU [] is already in use

If I check the value of $sku (with Tracy) it's always empty!

Any idea what could be wrong?

EDIT: if I remove the second hook, the field value is correctly preset with the page id!

$this->addHookAfter('Pages::added', $this, 'presetProductFields', ['priority' => 99]);
$this->addHookAfter('Pages::saveReady', $this, 'checkSKUUnique', ['priority' => 101]);

And this are the hook methods:

public function presetProductFields(HookEvent $event) {
    $snipwire = $this->wire('snipwire');
    if (!$snipwire) return;

    $page = $event->arguments(0);
    if ($snipwire->isProductTemplate($page->template)) {
        if ($page->hasfield('snipcart_item_id')) $page->setAndSave('snipcart_item_id', $page->id);
    }
}

/**
 * Check if the SKU value is unique across all product pages.
 * (Method triggered after Pages saveReady -> just before page is saved)
 *
 * @throws WireException
 *
 */
public function checkSKUUnique(HookEvent $event) {
    $snipwire = $this->wire('snipwire');
    if (!$snipwire) return;

    $page = $event->arguments(0);
    if ($snipwire->isProductTemplate($page->template)) {
        $field = $page->getField('snipcart_item_id');
        $sku = $page->snipcart_item_id; // SKU field value
        bd($sku);
        
        if ($page->isChanged('snipcart_item_id')) {
            $exists = $this->wire('pages')->get("snipcart_item_id=$sku");
            if ($exists->id) {
                // value is not unique!
                $error = $this->_('SKU must be unique'); 
                $exception = sprintf(
                    $this->_('SKU [%s] is already in use'),
                    $sku
                ); 
                $inputfield = $page->getInputfield($field);
                $inputfield->error($error); 
                throw new WireException($exception); // Prevent saving of non-unique value!
            }
        }
    }
}

 

Link to comment
Share on other sites

15 hours ago, Zeka said:

This looks promising! Thank you. The problem is, I can't use this new class in my module as the PW version requirement is set to 3.0.148. I could borrow the code from this class and build my own method. This would require to rewrite a lot of code instead of getting the hooks working properly.

Link to comment
Share on other sites

15 hours ago, bernhard said:

I knew there was something added lately, but then I didn't find it and thought maybe I was dreaming ?

0A7ayjQ.png

Thanks @bernhard, before I asked for help here, I searched for related information back and forth but couldn't find any relevant infos. The search results from your screenshot also didn't bring any light into this... ?

Link to comment
Share on other sites

Hi @Gadgetto the screencast was meant to show that I did search for the "unique" feature in the blog but didn't find relevant results ? It was not meant as something useful for your problem.

To your problem... Such things are a little hard when one is not directly in the code! Could you please setup two example hooks for the BASIC-PAGE template and the TITLE field. Almost everybody has those available for testing so we could just copy&paste your hooks into site/ready.php and provide tested solutions.

One thing that I saw in your code that could be slightly improved:

// your version:
if ($snipwire->isProductTemplate($page->template)) { ...

// better:
if($page->isSnipProduct) { ...
$wire->addHookProperty("Page::isSnipProduct", function($event) {
	$snipwire = ...
	$event->return = $snipwire->isProductTemplate($event->object->template);
}

That's just a little detail but IMHO overall that makes code more readable...

Another option would be to use the new Page Classes, but I guess that's no option for you because you because of the version requirement ? 

  • Like 1
Link to comment
Share on other sites

OK, here is the simplified code for testing in site/ready.php with "title" field used:

// To test, add this to your sites/ready.php

wire()->addHookAfter('Pages::added', 'presetTitleField', ['priority' => 99]);
wire()->addHookAfter('Pages::saveReady', 'checkTitleUnique');

function presetTitleField(HookEvent $event) {
    $page = $event->arguments(0);
    $page->setAndSave('title', 'Test' . $page->id);
}

function checkTitleUnique(HookEvent $event) {
    $page = $event->arguments(0);
    $field = $page->getField('title');
    $title = $page->title;
        
    if ($page->isChanged('title')) {
        $exists = wire('pages')->get("title=$title");
        if ($exists->id) {
            // value is not unique!
            $error = __('Title must be unique'); 
            $exception = sprintf(
                __('Title [%s] is already in use'),
                $title
            ); 
            $inputfield = $page->getInputfield($field);
            $inputfield->error($error); 
            throw new WireException($exception); // Prevent saving of non-unique value!
        }
    }
}

And thanks for the hint to extend the Page class with a new method!

Link to comment
Share on other sites

What I'm not sure about is: If I create a new page with the page editor, the creation process is split into 2 steps. In the first step you enter the title + name. Then you hit "Save". In the second step you can complete all other page fields and options.

Are the other page fields (beside title and name) already available for API in first step? Probably not. So my test code from last post could work with "title" field but not with the other page fields?

Link to comment
Share on other sites

This works for me:

// To test, add this to your sites/ready.php
wire()->addHookAfter('Pages::saveReady', 'checkiconUnique');

function checkiconUnique(HookEvent $event) {
  $page = $event->arguments(0);
  $field = $page->getField('icon');
  $icon = $page->icon;

  // preset icon
  // before the page is saved for the first time it does not have an id
  if(!$page->id) {
    $page->icon = "Preset icon " . uniqid();
  }
  else {
    if(!$page->isChanged('icon')) return;
    $exists = wire('pages')->get("id!=$page,icon=$icon");
    if($exists->id) {
      // value is not unique!
      $error = __('icon must be unique'); 
      $exception = sprintf(
        __('icon [%s] is already in use'),
        $icon
      ); 
      $inputfield = $page->getInputfield($field);
      $inputfield->error($error); 
      throw new WireException($exception); // Prevent saving of non-unique value!
    }
  }
}

Not sure if that works in all circumstances - that's why we build modules for such things. And not sure if a module by Ryan is really a 3rd party module that one should not include in his module ? But maybe it helps nonetheless...

I tested it with an "icon" field. You can simple find&replace that string to your fieldname. I made all occurrences lowercase to make that easier.

  • Like 1
Link to comment
Share on other sites

2 hours ago, Gadgetto said:

Are the other page fields (beside title and name) already available for API in first step?

    $this->addHookAfter('ProcessPageAdd::buildForm', function ($event) {
        $form = $event->return;
        // If adding page under particular parent
        if ($this->input->parent_id === '1041') {
            // Add inputfield to form after existing title field
            // If you name the inputfield the same as the field you want to populate
            // then the entered value will be saved automatically
            $f              = $this->modules->InputfieldText;
            $f->name        = 'myfieldname';
            $f->label       = 'My Field Label';
            $f->description = 'my field description';
            $f->required    = true;
            $f->attr('required', 1); // use HTML required attribute too
            $title_field        = $form->getChildByName('title');
            $title_field->label = 'Page Title';
            $title_field->description = "page title description";
            $form->insertAfter($f, $title_field);
            $event->return = $form;
        }
    });

I got this code a long time ago from somebody in this forum, and it works nicely. I can't find the original thread right now. It basically renders the field "myfieldname" in the first screen when you create a new page under parent id 1041. Not sure if that helps for your scenario.

  • Like 1
Link to comment
Share on other sites

@bernhard, @dragan,

Thanks a lot guys, I could fix it! It now runs bombproof  - this is the final code:

    public function checkSKUUnique(HookEvent $event) {
        $snipwire = $this->wire('snipwire');
        if (!$snipwire) return;
        
        $page = $event->arguments(0);
        if ($snipwire->isProductTemplate($page->template)) {
            $field = $page->getField('snipcart_item_id');
            $sku = $page->snipcart_item_id; // SKU field value
            if (!$sku) return; // <- ###### only had to add this line
            
            if ($page->isChanged('snipcart_item_id')) {
                $exists = $this->wire('pages')->get("snipcart_item_id=$sku, id!=$page, status<" . Page::statusTrash); // <- ###### and change this line
                if ($exists->id) {
                    // value is not unique!
                    $error = $this->_('SKU must be unique'); 
                    $exception = sprintf(
                        $this->_('SKU [%s] is already in use'),
                        $sku
                    ); 
                    $inputfield = $page->getInputfield($field);
                    $inputfield->error($error); 
                    throw new WireException($exception); // Prevent saving of non-unique value!
                }
            }
        }
    }

 

Link to comment
Share on other sites

Glad you solved it. Beside what I've already mentioned regarding isProductTemplate I have another suggestion: I think you could avoid neting IFs and make the code even more readable:

public function checkSKUUnique(HookEvent $event) {
  $snipwire = $this->wire('snipwire');
  if (!$snipwire) return;
  
  // only check snip products
  $page = $event->arguments(0);
  if(!$page->isSnipProduct) return;

  // exit if no changes
  if(!$page->isChanged('snipcart_item_id')) return;

  // don't check unsaved pages
  $field = $page->getField('snipcart_item_id');
  $sku = $page->snipcart_item_id; // SKU field value
  if(!$sku) return;

  // exit if value is unique
  $exists = $this->wire('pages')->get([
    ['snipcart_item_id', '=', $sku],
    ['id', '!=', $page],
    ['status', '<', Page::statusTrash],
  ]);
  if(!$exists->id) return;

  // value is not unique, show errors
  $error = $this->_('SKU must be unique');
  $page->getInputfield($field)->error($error);
  $exception = sprintf($this->_('SKU [%s] is already in use'), $sku);
  throw new WireException($exception); // Prevent saving of non-unique value!
}

 

  • Like 3
Link to comment
Share on other sites

5 hours ago, bernhard said:

I think you could avoid nesting IFs and make the code even more readable

You are right @bernhard. And I didn't even know I could set selectors via array! I'm still scratching on the surface of ProcessWire...

Code refactoring will be done when the module is in a stable state and I've implemented all necessary features. 

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

×
×
  • Create New...