10.04.2018 Views

Doctrine_manual-1-2-en

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 10: Compon<strong>en</strong>t Overview 186<br />

Explicit Validation<br />

You can explicitly trigger the validation for any record at any time. For this purpose<br />

<strong>Doctrine</strong>_Record provides the instance method <strong>Doctrine</strong>_Record::isValid(). This<br />

method returns a boolean value indicating the result of the validation. If the method returns<br />

false, you can inspect the error stack in the same way as se<strong>en</strong> above except that no exception<br />

is thrown, so you simply obtain the error stack of the record that didnt pass validation<br />

through <strong>Doctrine</strong>_Record::getErrorStack().<br />

The following code snippet shows an example of handling implicit validation which caused a<br />

<strong>Doctrine</strong>_Validator_Exception.<br />

Listing<br />

10-98<br />

// test.php<br />

// ...<br />

$user = new User();<br />

try {<br />

$user->username = str_repeat('t', 256);<br />

$user->Email->address = "drink@@notvalid..";<br />

$user->save();<br />

} catch(<strong>Doctrine</strong>_Validator_Exception $e) {<br />

$userErrors = $user->getErrorStack();<br />

$emailErrors = $user->Email->getErrorStack();<br />

foreach($userErrors as $fieldName => $errorCodes) {<br />

echo $fieldName . " - " . implode(', ', $errorCodes) . "\n";<br />

}<br />

}<br />

foreach($emailErrors as $fieldName => $errorCodes) {<br />

echo $fieldName . " - " . implode(', ', $errorCodes) . "\n";<br />

}<br />

You could also use $e->getInvalidRecords(). The direct way used above is just more<br />

simple wh<strong>en</strong> you know the records you're dealing with.<br />

You can also retrieve the error stack as a nicely formatted string for easy use in your<br />

applications:<br />

Listing<br />

10-99<br />

// test.php<br />

// ...<br />

echo $user->getErrorStackAsString();<br />

It would output an error string that looks something like the following:<br />

Listing<br />

10-100<br />

Validation failed in class User<br />

1 field had validation error:<br />

* 1 validator failed on username (l<strong>en</strong>gth)<br />

----------------- Brought to you by

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!