2

I have a user table with an enum field for gender with the options male / female. If I create a user an Exception is thrown if I try to set the gender to for example 'transgender'.

Is it possible to allow setting transgender to 'transgender' and only get a validation error if I call the validate() function? So it is validated together with the other fields?

Schema.xml:

<table name="user" idMethod="native" namespace="Models" package="Models">
    <column name="id" type="INTEGER" sqlType="INTEGER(11) UNSIGNED" primaryKey="true" autoIncrement="true" required="true"/>
    <column name="first_name" type="VARCHAR" required="true"/>
    <column name="mail" type="VARCHAR" required="true"/>
    <column name="gender" type="ENUM" valueSet="male, female"/>
    <behavior name="validate">
        <parameter name="rule1" value="{column: first_name, validator: NotNull}" />
        <parameter name="rule2" value="{column: mail, validator: NotNull}" />
        <parameter name="rule3" value="{column: gender, validator: NotNull}" />
        <parameter name="rule4" value="{column: gender, validator: ValidEnum}" />
    </behavior>
</table>

PHP code:

$user = new User();
$user->setFirstName('John');
$user->setMail('johndoe@gmail.com');
$user->setGender('transgender'); // currently throws an exception 
if ($user->validate()) {
    $user->save();
} else {
    // handle exception
}
Ivan
  • 2,463
  • 1
  • 20
  • 28
klaasjansen
  • 537
  • 1
  • 6
  • 20
  • I've got the same issue with a column of the type DATETIME. If I set it to an unvalid date, an Exception is thrown. This makes it impossible to use a DateTime validator. – klaasjansen Jan 12 '17 at 12:54
  • A simple solution would be to extend the setter and catch the exception there. – chocochaos Jan 23 '19 at 10:06

1 Answers1

0

Since you might get an exception, then perhaps wrap this in a try-catch block.

try {
    $user = new User();
    $user->setFirstName('John');
    $user->setMail('johndoe@gmail.com');
    $user->setGender('transgender'); // currently throws an exception 
    $user->save();
} catch (PropelException $e) {
    echo $e->getMessage(); // Value "transgender" is not accepted in this enumerated column
}
Qiniso
  • 2,587
  • 1
  • 24
  • 30