Jump to content

Unique Text Field


markus_blue_tomato
 Share

Recommended Posts

Is there a way to have a unique Textfield? A Textfield which value is unique to all other pages with the same template?

I found https://processwire.com/modules/fieldtype-text-unique/ but saw that it is not maintained for a long time.

I had in my mind, that some others here had this issue already but my search did not result in anything....

  • Like 1
Link to comment
Share on other sites

53 minutes ago, markus_blue_tomato said:

I found https://processwire.com/modules/fieldtype-text-unique/ but saw that it is not maintained for a long time.

Maybe there's nothing wrong with it that needs maintaining.

Alternatively you could use an ordinary text field and use a hook to validate the inputfield value:

$wire->addHookAfter('InputfieldText::processInput', function(HookEvent $event) {
	$inputfield = $event->object;
	$field = $inputfield->hasField;
	if($field && $field->name === 'text_unique') {
		// Look for existing page with the field value
		$value = $event->wire()->sanitizer->selectorValue($inputfield->value);
		$existing_page = $event->wire()->pages->get("text_unique=$value, template=news_item");
		if($existing_page->id) {
			// Show an error message
			$inputfield->error("Value '{$inputfield->value}' already in use on page '{$existing_page->title}'.");
			// Clear value
			$inputfield->value = '';
		}
	}
});

unique.gif.2bdf8fdc5a3b1b64c6f03df0311bcfa1.gif

  • Like 2
  • Thanks 1
Link to comment
Share on other sites

  • 3 weeks later...

Thanks for posting this, I was about to as something similar. I'm not sure the “Unique” status is a good fix to what I'm after doing. It looks like a hook per @Robin S‘s code would do the job nicely.

I love PW. One thing I do think would be nice though for a future version would be for the core to offer some of the data integrity features of a rational database but managed through template and page settings:

  • Something to mimic CASCADE and RESTRICT so that in a page reference, for example, you can restrict it being deleted if another page references it
  • Make a field (of fields) unique as above
  • 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

  • Recently Browsing   0 members

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