How to make a field as unique?
Hello,
What is the simplest way to make a field as unique in Typolight? (in the database script, in dca)?
By unique I mean : if the first element is named "test" no other can be named "test" again. The best would be to have a validator message, like the one for the "not null field" : "This field can not be left blank", but this time :"This value already exist, please choose another name". Or something like this...
Thanks
Re: How to make a field as unique?
add a 'save_callback' entry in your field definition:
Code:
'myfield' => array
(
'label' =>...,
'inputType' => 'text',
'save_callback' => array
(
array('myclass', 'checkUniqueness')
)
then create the callback
Code:
class myclass extends Backend {
public function __construct() {
parent::__construct();
$this->import('Database');
}
public function checkUniqueness($varValue, DataContainer $dc) {
// value check goes here
if ($recordExists) {
throw new Exception('field must be unique');
}
return $varValue
}
}
hope this helps
Re: How to make a field as unique?
Many ways for various objectives...
In the sql...to ensure unique entries into the database
Code:
UNIQUE KEY `name` (`name`)
In the DCA of your module in tl_whatever.php
Code:
'eval' => array('mandatory'=>true,'unique'=>true, 'maxlength'=>6, 'tl_class'=>'w50'),
To make a member email unique for instance...
In your modules DCA in tl_member.php
Code:
$GLOBALS['TL_DCA']['tl_member']['fields']['email']['eval']['unique'] = true;
Re: How to make a field as unique?
very good and easy! thanks I will test it!