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

ModelAdmin: Random Value for TextField when Creating new Object


3 Posts   981 Views


18 November 2010 at 1:31pm Community Member, 25 Posts


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();


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

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

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

      return $f;

thanks for your help in advance


18 November 2010 at 2:53pm Forum Moderator, 474 Posts

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

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


18 November 2010 at 3:01pm Community Member, 25 Posts

thanks a lot. that did the trick!