Jump to:

3428 Posts in 1056 Topics by 733 members

Data Model Questions

SilverStripe Forums » Data Model Questions » ModelAdmin: Random Value for TextField when Creating new Object

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

Page: 1
Go to End
Author Topic: 952 Views
  • Matze0681
    Avatar
    Community Member
    25 Posts

    ModelAdmin: Random Value for TextField when Creating new Object Link to this post

    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

  • simon_w
    Avatar
    Forum Moderator
    471 Posts

    Re: ModelAdmin: Random Value for TextField when Creating new Object Link to this post

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

  • Matze0681
    Avatar
    Community Member
    25 Posts

    Re: ModelAdmin: Random Value for TextField when Creating new Object Link to this post

    thanks a lot. that did the trick!

    952 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.