2

I have a model with unique field, as showed bellow. The problem is the field is optional and when it is null, I get doctrine's unique error message.

I was expecting it only to validate uniqueness of 'notnull' => true fields.

$this->hasColumn('filename', 'string', 40, array(
     'type' => 'string',
     'unique' => true,
     'length' => '40',
 ));

Thank you in advance.

Edit: I Disabled validation and it looks like the field is carrying a blank string instead of null:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'filename'

So the question now is: How do I enforce null values on blank values...

Edit 2: I did that as workaround. =/

public function preValidate()
{
    if(!$this->filename) {
        $this->filename = null;
    }
}
Marcelo
  • 1,702
  • 2
  • 24
  • 42

2 Answers2

3

It might be a better idea to extend the form, and override the post validator with your own custom method:

You would put this in the FileForm (or whatever your form name is called):

$this->validatorSchema->setPostValidator(
  new myValidatorDoctrineUniqueWithNull(array('model' => 'File', 'column' => array('filename')))
);

Then you would create your own validator (as defined above), like so:

class myValidatorDoctrineUniqueWithNull extends sfValidatorDoctrineUnique
{
  protected function doClean($values)
  {
    // if the user passes an empty value, assume it must be null in the database
    // which is an allowed "non-unique" value.
    $column = $this->getOption('column');
    if (!$values[$column])
    {
      return $values;
    }

    return parent::doClean($values);
  }
}

If you build a validator, it is resuable if you ever run into the situation again.

Slickrick12
  • 897
  • 1
  • 7
  • 21
  • I'm assuming you are using symfony 1.4 by the way. If not, the process would still be very similar. – Slickrick12 Nov 30 '11 at 22:05
  • Great solution. But to work i replaced $column = $this->getOption('column'); for $column = current($this->getOption('column')); beacuse the getColumn return a Array. – André Morales Apr 11 '14 at 14:07
0
class myValidatorDoctrineUniqueWithNull extends sfValidatorDoctrineUnique
{
    protected function doClean($values)
    {
        // if the user passes an empty value, assume it must be null in the database
        // which is an allowed "non-unique" value.
        $column = current($this->getOption('column'));

        if (!$values[$column])
        {
            // Solves the problem of the unique index in mysql, because doctrine uses a empty string
            if(empty($values[$column]))
                $values[$column] = null;
            return $values;
        }

        return parent::doClean($values);
    }
}

In addition to the solution provided by Slickrick12.

André Morales
  • 478
  • 3
  • 6