Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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.

Maelan

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

Good luck



203
Accepted
answer

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