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.

General Questions

General questions about getting started with SilverStripe that don't fit in any of the categories above.

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

DataObject validation for duplicate record


Reply

6 Posts   837 Views

Avatar
congii

14 January 2013 at 3:30pm Community Member, 6 Posts

Hi,

I would like to check if a certain record already exist before adding it in the table. Show meaningful error message
to the user too if it failes. I am using DataObject and ModelAdmin to manage those tables.

class Country extends DataObject {

static $db = array('CountryName');

....

//check if country exist before saving

....

}

Is there anyone who would like to share some idea how to accomplish this?

Thanks!

Avatar
lx

15 January 2013 at 1:18pm Community Member, 83 Posts

The netefxvalidator works well with modeladmin, for ss 2.4 and 3.0
The unique rule is what you are looking for.

You have to add the validator in a function getCMSValidator

Download: https://github.com/lx-berlin/NetefxValidator
Documentation: http://www.netefx.de/Silverstripe-NetefxValidator.php

Lx

Avatar
soolan

6 April 2013 at 7:44pm Community Member, 11 Posts

Hello lx,
Can you share your thoughts on vlaidation on CMS (backend) please.

Assuming I have a Product DataObject, containing name, price and date fields,
how can I validate these fields while I'm adding a new product at the backend.

A piece of sample code for validator function would be very helpful.
Thank you very much

Avatar
swaiba

8 April 2013 at 12:20am Forum Moderator, 1796 Posts

Please read this thread for a code example...

http://www.silverstripe.org/general-questions/show/17007

Avatar
lx

8 April 2013 at 12:40am Community Member, 83 Posts

Hi soolan,

here are some example rules, that are a little bit more complex than just "required".
I hope they are working.

regards
lx

class Product extends DataObject {

...

public function getCMSValidator() {

$rule_Name_required = new NetefxValidatorRuleREQUIRED ("Name", "The name of the product is required.");
$rule_Price_higher_zero = new NetefxValidatorRuleGREATER ("Price", "You need to enter a price higher than 0.", null, "0");
$rule_Date_required = new NetefxValidatorRuleREQUIRED ("Date", "The date is required.");
$rule_Date_in_future = NetefxValidatorRuleFUNCTION("Date", "The date has to be in the future.", null,array('NetefxValidatorLibraryDate', 'DateIsMinDaysAfterToday', array('date' => 'Date', 'min' => 1)));

$validator = new NetefxValidator($rule_Name_required, $rule_Price_higher_zero, $rule_Date_in_future, $rule_Date_required);

return $validator;
}

...

}

Avatar
soolan

8 April 2013 at 2:12pm Community Member, 11 Posts

Thank you very much guys.