Browse Source

Add fieldNames() to Form contexts.

Generating inputs based on only an entity requires knowing the field
names, so we'll need a way to reflect that data as well.
Mark Story 12 years ago
parent
commit
8451e716b6

+ 9 - 0
src/View/Form/ArrayContext.php

@@ -175,6 +175,15 @@ class ArrayContext implements ContextInterface {
 	}
 
 /**
+ * {@inheritDoc}
+ */
+	public function fieldNames() {
+		$schema = $this->_context['schema'];
+		unset($schema['_constraints'], $schema['_indexes']);
+		return array_keys($schema);
+	}
+
+/**
  * Get the abstract field type for a given field name.
  *
  * @param string $field A dot separated path to get a schema type for.

+ 7 - 0
src/View/Form/ContextInterface.php

@@ -62,6 +62,13 @@ interface ContextInterface {
 	public function isRequired($field);
 
 /**
+ * Get the fieldnames of the top level object in this context.
+ *
+ * @return array A list of the field names in the context.
+ */
+	public function fieldNames();
+
+/**
  * Get the abstract field type for a given field name.
  *
  * @param string $field A dot separated path to get a schema type for.

+ 12 - 0
src/View/Form/EntityContext.php

@@ -318,6 +318,18 @@ class EntityContext implements ContextInterface {
 	}
 
 /**
+ * Get the field names from the top level entity.
+ *
+ * If the context is for an array of entities, the 0th index will be used.
+ *
+ * @return array Array of fieldnames in the table/entity.
+ */
+	public function fieldNames() {
+		$table = $this->_getTable('0');
+		return $table->schema()->columns();
+	}
+
+/**
  * Get the validator associated to an entity based on naming
  * conventions.
  *

+ 7 - 0
src/View/Form/NullContext.php

@@ -80,6 +80,13 @@ class NullContext implements ContextInterface {
 /**
  * {@inheritDoc}
  */
+	public function fieldNames() {
+		return [];
+	}
+
+/**
+ * {@inheritDoc}
+ */
 	public function type($field) {
 		return null;
 	}

+ 14 - 0
tests/TestCase/View/Form/EntityContextTest.php

@@ -819,4 +819,18 @@ class EntityContextTest extends TestCase {
 		$comments->validator('custom', $validator);
 	}
 
+/**
+ * Test the fieldnames method.
+ *
+ * @return void
+ */
+	public function testFieldNames() {
+		$context = new EntityContext($this->request, [
+			'entity' => new Entity(),
+			'table' => 'Articles',
+		]);
+		$articles = TableRegistry::get('Articles');
+		$this->assertEquals($articles->schema()->columns(), $context->fieldNames());
+	}
+
 }