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.

Data Model Questions /

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

ModelAdmin: Random Value for TextField when Creating new Object


Go to End
Reply


3 Posts   1185 Views

Avatar
Matze0681

Community Member, 25 Posts

18 November 2010 at 1:31pm

hi,

i am trying to generate a random string value when i open a new Object in ModelAdmin. (Create ObjectXY)

i use getCMSFields to remove the Field from the Tab, Generate a Random String and want to add the Field again with the Random Value.

but when i add the field again like that:

$f->addFieldToTab('Root.Main',new TextField('Code','PromoCode',$randomUniqueCode));

.. the textfield stays empty :(

here´s my full getCMSFields function:

	function getCMSFields(){
		$f = parent::getCMSFields();

		$f->removeFieldFromTab('Root','Code');

		//generate code first time
		$randomUniqueCode = $this->generateRandomCode(10);

		$existingCodes = DataObject::get('PromoCode');
		if(count($existingCodes)){
			foreach($existingCodes as $code){
				if($randomUniqueCode == $code->Code)
					$randomUniqueCode = $this->generateRandomCode(10);
				else
					break;
			}
		}

		if($this->ID == 0)
			$f->addFieldToTab('Root.Main',new TextField('Code','PromoCode',$randomUniqueCode));
		else
			$f->addFieldToTab('Root.Main',new TextField('Code','PromoCode',$this->Code));


		return $f;
	}

thanks for your help in advance
matze

Avatar
(deleted)

Community Member, 473 Posts

18 November 2010 at 2:53pm

You'll want to use the populateDefaults method. Something like:

public function populateDefaults() {
	parent::populateDefaults();
	do {
		$this->Code = $this->generateRandomCode(10);
	} while(DB::Query('SELECT COUNT("ID") FROM "PromoCode" WHERE "Code" = \'' . $this->Code . '\' LIMIT 1')->value());
}

Avatar
Matze0681

Community Member, 25 Posts

18 November 2010 at 3:01pm

thanks a lot. that did the trick!