2016-02-22 02:13:35 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace SilverStripe\Forms\Schema;
|
|
|
|
|
|
|
|
use Convert;
|
|
|
|
use Form;
|
|
|
|
|
2016-03-03 00:03:38 +01:00
|
|
|
/**
|
|
|
|
* Class FormSchema
|
|
|
|
* @package SilverStripe\Forms\Schema
|
|
|
|
*
|
|
|
|
* Represents a {@link Form} as structured data which allows a frontend library to render it.
|
|
|
|
* Includes information about the form as well as its fields.
|
|
|
|
* Can create a "schema" (structure only) as well as "state" (data only).
|
|
|
|
*/
|
2016-02-22 02:13:35 +01:00
|
|
|
class FormSchema {
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Gets the schema for this form as a nested array.
|
|
|
|
*
|
|
|
|
* @param Form $form
|
2016-02-29 01:50:59 +01:00
|
|
|
* @return array
|
2016-02-22 02:13:35 +01:00
|
|
|
*/
|
|
|
|
public function getSchema(Form $form) {
|
|
|
|
$request = $form->controller()->getRequest();
|
|
|
|
|
|
|
|
$schema = [
|
|
|
|
'name' => $form->getName(),
|
2016-04-21 04:38:02 +02:00
|
|
|
'id' => $form->FormName(),
|
|
|
|
'action' => $form->FormAction(),
|
|
|
|
'method' => $form->FormMethod(),
|
|
|
|
// @todo Not really reliable. Refactor into action on $this->Link('schema')
|
2016-02-22 02:13:35 +01:00
|
|
|
'schema_url' => $request->getUrl(),
|
|
|
|
'attributes' => $form->getAttributes(),
|
|
|
|
'data' => [],
|
|
|
|
'fields' => [],
|
|
|
|
'actions' => []
|
|
|
|
];
|
|
|
|
|
|
|
|
foreach ($form->Actions() as $action) {
|
|
|
|
$schema['actions'][] = $action->getSchemaData();
|
|
|
|
}
|
|
|
|
|
2016-03-21 11:12:07 +01:00
|
|
|
// TODO Implemented nested fields and use Fields() instead
|
|
|
|
foreach ($form->Fields()->dataFields() as $field) {
|
|
|
|
$schema['fields'][] = $field->getSchemaData();
|
2016-02-22 02:13:35 +01:00
|
|
|
}
|
|
|
|
|
2016-02-29 01:50:59 +01:00
|
|
|
return $schema;
|
2016-02-22 02:13:35 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Gets the current state of this form as a nested array.
|
|
|
|
*
|
2016-03-01 04:15:47 +01:00
|
|
|
* @param Form $form
|
2016-02-29 01:50:59 +01:00
|
|
|
* @return array
|
2016-02-22 02:13:35 +01:00
|
|
|
*/
|
|
|
|
public function getState(Form $form) {
|
2016-02-29 01:50:59 +01:00
|
|
|
$state = [
|
2016-04-21 04:38:02 +02:00
|
|
|
'id' => $form->FormName(),
|
2016-02-29 01:50:59 +01:00
|
|
|
'fields' => [],
|
|
|
|
'messages' => []
|
|
|
|
];
|
2016-02-22 02:13:35 +01:00
|
|
|
|
2016-03-01 04:15:47 +01:00
|
|
|
foreach ($form->Fields()->dataFields() as $field) {
|
|
|
|
$state['fields'][] = $field->getSchemaState();
|
|
|
|
}
|
|
|
|
|
|
|
|
if($form->Message()) {
|
|
|
|
$state['messages'][] = [
|
|
|
|
'value' => $form->Message(),
|
|
|
|
'type' => $form->MessageType(),
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
2016-02-29 01:50:59 +01:00
|
|
|
return $state;
|
2016-02-22 02:13:35 +01:00
|
|
|
}
|
|
|
|
}
|