Skip to content

Commit

Permalink
Documentation and test for Entity::errors()
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Nov 20, 2013
1 parent edd3796 commit f82ac1b
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
30 changes: 30 additions & 0 deletions Cake/ORM/Entity.php
Expand Up @@ -479,6 +479,35 @@ public function validate(Validator $validator, array $fieldList = []) {
return empty($this->_errors);
}

/**
* Sets the error messages for a field or a list of fields. When called
* without the second argument it returns the validation
* errors for the specified fields. If called with no arguments it returns
* all the validation error messages stored in this entity.
*
* ### Example
*
* {{{
* // Sets the error messages for a single field
* $entity->errors('salary', ['must be numeric', 'must be a positive number']);
*
* // Returns the error messages for a single field
* $entity->errors('salary');
*
* // Returns all error messages indexed by field name
* $entity->errors();
*
* // Sets the error messages for multiple fields at once
* $entity->errors(['salary' => ['message'], 'name' => ['another message']);
* }}}
*
* When used as a setter, this method will return this entity instance for method
* chaining.
*
* @param string|array $field
* @param string|array $errors The errors to be set for $field
* @return array|Entity
*/
public function errors($field = null, $errors = null) {
if ($field === null) {
return $this->_errors;
Expand All @@ -498,4 +527,5 @@ public function errors($field = null, $errors = null) {

return $this;
}

}
27 changes: 27 additions & 0 deletions Cake/Test/TestCase/ORM/EntityTest.php
Expand Up @@ -712,4 +712,31 @@ public function testValidateNoFieldList() {
$this->assertTrue($entity->validate($validator));
$this->assertEquals([], $entity->errors());
}

/**
* Tests the errors method
*
* @return void
*/
public function testErrors() {
$entity = new Entity;
$this->assertEmpty($entity->errors());
$this->assertSame($entity, $entity->errors('foo', 'bar'));
$this->assertEquals(['bar'], $entity->errors('foo'));

$entity->errors('foo', 'other error');
$this->assertEquals(['other error'], $entity->errors('foo'));

$entity->errors('bar', ['something', 'bad']);
$this->assertEquals(['something', 'bad'], $entity->errors('bar'));

$expected = ['foo' => ['other error'], 'bar' => ['something', 'bad']];
$this->assertEquals($expected, $entity->errors());

$errors = ['foo' => ['something'], 'bar' => 'else', 'baz' => ['error']];
$this->assertSame($entity, $entity->errors($errors));
$errors['bar'] = ['else'];
$this->assertEquals($errors, $entity->errors());
}

}

0 comments on commit f82ac1b

Please sign in to comment.