Adrian
Adrian

Reputation: 1002

Generating random string by TypoScript

Is it possible to auto generate a mixed string of digits and letters by TypoScript, e.g. 12A54 or something similar?

Upvotes: 5

Views: 2298

Answers (3)

tmt
tmt

Reputation: 8614

As already mentioned, there is no such functionality in Typoscript and so the preferred method is to use some simle PHP function as suggested in other answers.

However, there is a cheat and that would be to use MySQL. Mind you, that it's a solution only if you absolutely cannot (for a reason that I really cannot think of) write a piece of custom PHP. Take it rather as an academic answer than a practical one.

temp.random = CONTENT
temp.random {
  table = tt_content
  select {
    pidInList = 1
    recursive = 99
    max = 1
    selectFields = SUBSTRING(MD5(RAND()) FROM 1 FOR 6) AS random_string
  }
  renderObj = TEXT
  renderObj {
    field = random_string
    case = upper
  }
}

NOTES:

  1. pidInList must point to an existing page.
  2. The MySQL command is really just an example as the string would never contain letters G-Z. I'm sure it's possible to come up with a better string generated by MySQL.

Upvotes: 5

biesior
biesior

Reputation: 55798

Patching TYPO3 sources for such easy tasks is wrong idea. After the next source upgrade you'll lose your changes.

Instead it's better to include an easy PHP script where you can render what you need check TSREF

Upvotes: 3

Mateng
Mateng

Reputation: 3734

I'd prefer a userFunc to a php include script. For example, you can pass parameters to a user function.

Typoscript:

includeLibs.generateInvoiceNo= fileadmin/scripts/generateInvoiceNo.php
temp.invoiceNo = USER
temp.invoiceNo {
  userFunc =user_generateInvoiceNo->main
}

PHP:
fileadmin/scripts/generateInvoiceNo.php

<?
class user_generateInvoiceNo {
    var $cObj;// The backReference to the mother cObj object set at call time
    /**
    * Call it from a USER cObject with 'userFunc = user_generateInvoiceNo->main'
    */
    function main($content,$conf){
        $length = 6;
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $number=substr(str_shuffle($chars),0,$length);
        return $number;
    }
}
?>

Credits:

Upvotes: 7

Related Questions