I am creating a new data type, 'duration'. The value will be a duration string that is used by a DateIntervale object.

The value is a string, but with a specified format. I'm assuming that due to it being a string, for my @DataType I should either extend StringData, or PrimitiveData. And I would like to add required validation to this data to ensure that the value contained is in the correct format.

I've been reading through documentation, and reverse engineering other @DataType objects, but I've not been able to find what I'm looking for. So what I want to specifically ask:

  1. Should I extend StringData, or is it better to extend PrimitiveData?

  2. How/where can I add a constraint onto this data. By this I mean, what method should I use to ensure that when someone calls setValue() using this data, the string can be validated using a regex to ensure it's the proper format.

  3. If the value is not the proper format, how is this handled? Is there a way to call an error? Should I throw an Exception? Or should I set a default value instead of the value that was supposed to be submitted?

  4. Am I looking at this the right way?

Thank you.

1 Answer 1


In abstract class PrimitiveBase that uses PrimitiveInterface... which StringData entends you can see the PrimitiveInterface use of PrimitiveInterface methods:

getValue(); , setValue($value);, getCastedValue();

so you can safely do ether however ... Personally as your data is realy a string I would go with the extend StringData option

and call parent functions like

 public function getValue() {
   return parent::getValue();

 public function setValue($value) {
   $new_value = $this->getREGXCRAXY($value);

   return $this->parent->setValue($new_value);

 public function  getREGXCRAXY($value) {
    do the things.
  if value !== valid 
 throw new \Exception('Invalid data dude must be in format xyz');
  return $new_formated_value; 

no i think it is proper to throw the exception because then the person can catch it in an event subscriber .. or learn the right way to set the data.

  • Thanks Taggart! Very clear answer, and exactly what I needed. Much appreciated.
    – Jaypan
    May 9, 2018 at 5:50
  • 1
    No thank you! you helped me and a lot of other people on drupal.org - (for a long time) glad I could re-pay the favour !
    – taggartJ
    May 9, 2018 at 6:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.