Skip to content
Browse files

Add validator as a string.

Using a string to name the validator is often much simpler than
providing the validator.
  • Loading branch information...
1 parent ccd4b8c commit 5cdef0d31228b53ea50c1d5aa7bd42954468d4f3 @markstory markstory committed
Showing with 40 additions and 3 deletions.
  1. +14 −1 src/View/Form/EntityContext.php
  2. +26 −2 tests/TestCase/View/Form/EntityContextTest.php
View
15 src/View/Form/EntityContext.php
@@ -16,6 +16,7 @@
use Cake\Network\Request;
use Cake\ORM\Entity;
+use Cake\ORM\TableRegistry;
use Cake\Validation\Validator;
use Traversable;
@@ -70,6 +71,13 @@ class EntityContext {
protected $_validators = [];
/**
+ * A dictionary of tables
+ *
+ * @var array
+ */
+ protected $_tables = [];
+
+/**
* Constructor.
*
* @param Cake\Network\Request
@@ -98,11 +106,16 @@ protected function _prepare() {
if (is_string($this->_context['table'])) {
$plural = $this->_context['table'];
}
- $this->_pluralName = $plural;
+ $table = TableRegistry::get($plural);
if (is_object($this->_context['validator'])) {
$this->_validators['_default'] = $this->_context['validator'];
+ } elseif (is_string($this->_context['validator'])) {
+ $this->_validators['_default'] = $table->validator($this->_context['validator']);
}
+
+ $this->_pluralName = $plural;
+ $this->_tables[$plural] = $table;
}
/**
View
28 tests/TestCase/View/Form/EntityContextTest.php
@@ -154,8 +154,32 @@ public function testIsRequired() {
$this->assertFalse($context->isRequired('nope'));
}
- public function testIsRequiredCustomValidationMethod() {
- $this->markTestIncomplete();
+/**
+ * Test validator as a string.
+ *
+ * @return void
+ */
+ public function testIsRequiredStringValidator() {
+ $articles = TableRegistry::get('Articles');
+
+ $validator = $articles->validator();
+ $validator->add('title', 'minlength', [
+ 'rule' => ['minlength', 10]
+ ])
+ ->add('body', 'maxlength', [
+ 'rule' => ['maxlength', 1000]
+ ])->allowEmpty('body');
+
+ $context = new EntityContext($this->request, [
+ 'entity' => new Entity(),
+ 'table' => 'Articles',
+ 'validator' => 'default',
+ ]);
+
+ $this->assertTrue($context->isRequired('Articles.title'));
+ $this->assertTrue($context->isRequired('title'));
+ $this->assertFalse($context->isRequired('Articles.body'));
+ $this->assertFalse($context->isRequired('body'));
}
public function testIsRequiredAssociated() {

0 comments on commit 5cdef0d

Please sign in to comment.
Something went wrong with that request. Please try again.