Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Data Model Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Why indexed columns not validating in SIilverstripe?


Go to End


2 Posts   1162 Views

Avatar
Developer123

Community Member, 1 Post

23 June 2016 at 12:26pm

I followed the documentation and created a unique index on a columns '"MyField","MyOtherField"' but the ModelAdmin is still accepting duplicate entries for the indexed column. Why is it not validating the entries? Below is the code for reference.

<?php

class MyTestObject extends DataObject {

private static $db = array(
'MyField' => 'Varchar',
'MyOtherField' => 'Varchar',
);

private static $indexes = array(
'MyIndexName' => array(
'type' => 'unique',
'value' => '"MyField","MyOtherField"'
)
);
}

Avatar
Devlin

Community Member, 344 Posts

23 June 2016 at 8:42pm

Edited: 23/06/2016 10:02pm

I can confirm that ModelAdmin does not validate unique indexes. However, it does not allow duplicate entries because a fatal error will prevent this. Additionally an empty row will be created which is not nice at all.

I think this is worth raising an issue on GitHub.

class MyTestObject extends DataObject {
	private static $db = array(
		'MyField' => 'Varchar',
		'MyOtherField' => 'Varchar',
	);
	private static $indexes = array(
		'MyIndexName' => array(
			'type' => 'unique',
			'value' => '"MyField","MyOtherField"'
		)
	);

	public function validate() {
		$valid = parent::validate();

		$duplicate = MyTestObject::get()
				->filter(array(
					'MyField' => $this->MyField,
					'MyOtherField' => $this->MyOtherField,
				))
				->exclude('ID', $this->ID);
		if ($duplicate->exists()) {
			$valid->error('duplicate entry');
		}

		return $valid;
	}
}