We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

String length validation from model annotation

Hello, I get many "SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column * ... " and I have way too many classes to validate each column manually, but all my models have the length of the strings columns specified in the annotations. All my classes inherit from a main class where I do my general validations in a beforeInsert() function

I there a way to validate the string length against the annotation length before insert ?

Thanks for your help.


You can access by meta data from the model to check it. Model::getModelMetaData()

Good luck


Alright, I've found a way, not very straight forward but that will work for me. In case anyone needs to truncate strings before insertion in db according to column length, here's how I went :

public function beforeValidation()
        $reader = new MemoryAdapter();
        $reflector = $reader->get(get_class($this));
        $annotations = $reflector->getPropertiesAnnotations();

        foreach ($this->getModelsMetaData()->getAttributes($this) as $property) {
            $value = $this->$property;
            $annotation = $annotations[$property]->get("Column");

            /* All my previous validation here */

            if ($annotation && $annotation->hasArgument("length")) {
                $length = $annotation->getArgument("length");
                if (strlen($value) > $length) {
                    $this->$property = substr($value, 0, $length);