Docblock and coding conventions for GridField related classes.

This commit is contained in:
Will Rossiter 2013-03-05 10:29:27 +13:00
parent 36d3303e1b
commit 1ddd1ddc47
4 changed files with 245 additions and 131 deletions

View File

@ -55,6 +55,8 @@ class GridField extends FormField {
/** /**
* The components list * The components list
*
* @var array
*/ */
protected $components = array(); protected $components = array();
@ -68,9 +70,14 @@ class GridField extends FormField {
/** /**
* Map of callbacks for custom data fields * Map of callbacks for custom data fields
*
* @var array
*/ */
protected $customDataFields = array(); protected $customDataFields = array();
/**
* @var string
*/
protected $name = ''; protected $name = '';
/** /**
@ -222,12 +229,14 @@ class GridField extends FormField {
* Get the current GridState_Data or the GridState * Get the current GridState_Data or the GridState
* *
* @param bool $getData - flag for returning the GridState_Data or the GridState * @param bool $getData - flag for returning the GridState_Data or the GridState
*
* @return GridState_data|GridState * @return GridState_data|GridState
*/ */
public function getState($getData=true) { public function getState($getData = true) {
if($getData) { if($getData) {
return $this->state->getData(); return $this->state->getData();
} }
return $this->state; return $this->state;
} }
@ -465,11 +474,16 @@ class GridField extends FormField {
/** /**
* Add additional calculated data fields to be used on this GridField * Add additional calculated data fields to be used on this GridField
* @param array $fields a map of fieldname to callback. The callback will bed passed the record as an argument. *
* @param array $fields a map of fieldname to callback. The callback will
* be passed the record as an argument.
*/ */
public function addDataFields($fields) { public function addDataFields($fields) {
if($this->customDataFields) $this->customDataFields = array_merge($this->customDataFields, $fields); if($this->customDataFields) {
else $this->customDataFields = $fields; $this->customDataFields = array_merge($this->customDataFields, $fields);
} else {
$this->customDataFields = $fields;
}
} }
/** /**
@ -580,9 +594,11 @@ class GridField extends FormField {
*/ */
protected function buildColumnDispatch() { protected function buildColumnDispatch() {
$this->columnDispatch = array(); $this->columnDispatch = array();
foreach($this->getComponents() as $item) { foreach($this->getComponents() as $item) {
if($item instanceof GridField_ColumnProvider) { if($item instanceof GridField_ColumnProvider) {
$columns = $item->getColumnsHandled($this); $columns = $item->getColumnsHandled($this);
foreach($columns as $column) { foreach($columns as $column) {
$this->columnDispatch[$column][] = $item; $this->columnDispatch[$column][] = $item;
} }
@ -603,14 +619,19 @@ class GridField extends FormField {
// Update state from client // Update state from client
$state = $this->getState(false); $state = $this->getState(false);
if(isset($fieldData['GridState'])) $state->setValue($fieldData['GridState']);
if(isset($fieldData['GridState'])) {
$state->setValue($fieldData['GridState']);
}
// Try to execute alter action // Try to execute alter action
foreach($data as $k => $v) { foreach($data as $k => $v) {
if(preg_match('/^action_gridFieldAlterAction\?StateID=(.*)/', $k, $matches)) { if(preg_match('/^action_gridFieldAlterAction\?StateID=(.*)/', $k, $matches)) {
$id = $matches[1]; $id = $matches[1];
$stateChange = Session::get($id); $stateChange = Session::get($id);
$actionName = $stateChange['actionName']; $actionName = $stateChange['actionName'];
$args = isset($stateChange['args']) ? $stateChange['args'] : array(); $args = isset($stateChange['args']) ? $stateChange['args'] : array();
$html = $this->handleAlterAction($actionName, $args, $data); $html = $this->handleAlterAction($actionName, $args, $data);
// A field can optionally return its own HTML // A field can optionally return its own HTML
@ -750,31 +771,31 @@ class GridField extends FormField {
class GridField_FormAction extends FormAction { class GridField_FormAction extends FormAction {
/** /**
*
* @var GridField * @var GridField
*/ */
protected $gridField; protected $gridField;
/** /**
*
* @var array * @var array
*/ */
protected $stateValues; protected $stateValues;
/** /**
*
* @var array * @var array
*/ */
//protected $stateFields = array();
protected $actionName;
protected $args = array(); protected $args = array();
/**
* @var string
*/
protected $actionName;
/**
* @var boolean
*/
public $useButtonTag = true; public $useButtonTag = true;
/** /**
*
* @param GridField $gridField * @param GridField $gridField
* @param type $name * @param type $name
* @param type $label * @param type $label
@ -785,11 +806,13 @@ class GridField_FormAction extends FormAction {
$this->gridField = $gridField; $this->gridField = $gridField;
$this->actionName = $actionName; $this->actionName = $actionName;
$this->args = $args; $this->args = $args;
parent::__construct($name, $title); parent::__construct($name, $title);
} }
/** /**
* urlencode encodes less characters in percent form than we need - we need everything that isn't a \w * urlencode encodes less characters in percent form than we need - we
* need everything that isn't a \w.
* *
* @param string $val * @param string $val
*/ */
@ -806,13 +829,17 @@ class GridField_FormAction extends FormAction {
return '%'.dechex(ord($match[0])); return '%'.dechex(ord($match[0]));
} }
/**
* @return array
*/
public function getAttributes() { public function getAttributes() {
// Store state in session, and pass ID to client side // Store state in session, and pass ID to client side.
$state = array( $state = array(
'grid' => $this->getNameFromParent(), 'grid' => $this->getNameFromParent(),
'actionName' => $this->actionName, 'actionName' => $this->actionName,
'args' => $this->args, 'args' => $this->args,
); );
$id = preg_replace('/[^\w]+/', '_', uniqid('', true)); $id = preg_replace('/[^\w]+/', '_', uniqid('', true));
Session::set($id, $state); Session::set($id, $state);
$actionData['StateID'] = $id; $actionData['StateID'] = $id;
@ -837,10 +864,12 @@ class GridField_FormAction extends FormAction {
protected function getNameFromParent() { protected function getNameFromParent() {
$base = $this->gridField; $base = $this->gridField;
$name = array(); $name = array();
do { do {
array_unshift($name, $base->getName()); array_unshift($name, $base->getName());
$base = $base->getForm(); $base = $base->getForm();
} while ($base && !($base instanceof Form)); } while ($base && !($base instanceof Form));
return implode('.', $name); return implode('.', $name);
} }
} }

View File

@ -1,17 +1,18 @@
<?php <?php
/** /**
* Adds an "Print" button to the bottom or top of a GridField.
*
* @package framework * @package framework
* @subpackage gridfield * @subpackage gridfield
*/ */
/**
* Adds an "Print" button to the bottom or top of a GridField.
*/
class GridFieldPrintButton implements GridField_HTMLProvider, GridField_ActionProvider, GridField_URLHandler { class GridFieldPrintButton implements GridField_HTMLProvider, GridField_ActionProvider, GridField_URLHandler {
/** /**
* @var array Map of a property name on the printed objects, with values being the column title in the CSV file. * @var array Map of a property name on the printed objects, with values
* Note that titles are only used when {@link $csvHasHeader} is set to TRUE. * being the column title in the CSV file.
*
* Note that titles are only used when {@link $csvHasHeader} is set to TRUE
*/ */
protected $printColumns; protected $printColumns;
@ -21,7 +22,9 @@ class GridFieldPrintButton implements GridField_HTMLProvider, GridField_ActionPr
protected $printHasHeader = true; protected $printHasHeader = true;
/** /**
* Fragment to write the button to * Fragment to write the button to.
*
* @var string
*/ */
protected $targetFragment; protected $targetFragment;
@ -36,6 +39,10 @@ class GridFieldPrintButton implements GridField_HTMLProvider, GridField_ActionPr
/** /**
* Place the print button in a <p> tag below the field * Place the print button in a <p> tag below the field
*
* @param GridField
*
* @return array
*/ */
public function getHTMLFragments($gridField) { public function getHTMLFragments($gridField) {
$button = new GridField_FormAction( $button = new GridField_FormAction(
@ -45,21 +52,34 @@ class GridFieldPrintButton implements GridField_HTMLProvider, GridField_ActionPr
'print', 'print',
null null
); );
$button->setAttribute('data-icon', 'grid_print'); $button->setAttribute('data-icon', 'grid_print');
$button->addExtraClass('gridfield-button-print'); $button->addExtraClass('gridfield-button-print');
//$button->addExtraClass('no-ajax');
return array( return array(
$this->targetFragment => '<p class="grid-print-button">' . $button->Field() . '</p>', $this->targetFragment => '<p class="grid-print-button">' . $button->Field() . '</p>',
); );
} }
/** /**
* print is an action button * Print is an action button.
*
* @param GridField
*
* @return array
*/ */
public function getActions($gridField) { public function getActions($gridField) {
return array('print'); return array('print');
} }
/**
* Handle the print action.
*
* @param GridField
* @param string
* @param array
* @param array
*/
public function handleAction(GridField $gridField, $actionName, $arguments, $data) { public function handleAction(GridField $gridField, $actionName, $arguments, $data) {
if($actionName == 'print') { if($actionName == 'print') {
return $this->handlePrint($gridField); return $this->handlePrint($gridField);
@ -67,7 +87,10 @@ class GridFieldPrintButton implements GridField_HTMLProvider, GridField_ActionPr
} }
/** /**
* it is also a URL * Print is accessible via the url
*
* @param GridField
* @return array
*/ */
public function getURLHandlers($gridField) { public function getURLHandlers($gridField) {
return array( return array(
@ -82,15 +105,20 @@ class GridFieldPrintButton implements GridField_HTMLProvider, GridField_ActionPr
set_time_limit(60); set_time_limit(60);
Requirements::clear(); Requirements::clear();
Requirements::css(FRAMEWORK_DIR . '/css/GridField_print.css'); Requirements::css(FRAMEWORK_DIR . '/css/GridField_print.css');
if($data = $this->generatePrintData($gridField)){ if($data = $this->generatePrintData($gridField)){
return $data->renderWith("GridField_print"); return $data->renderWith("GridField_print");
} }
} }
/** /**
* Export core. * Return the columns to print
*/ *
public function generatePrintData($gridField) { * @param GridField
*
* @return array
*/
protected function getPrintColumnsForGridField(GridField $gridField) {
if($this->printColumns) { if($this->printColumns) {
$printColumns = $this->printColumns; $printColumns = $this->printColumns;
} else if($dataCols = $gridField->getConfig()->getComponentByType('GridFieldDataColumns')) { } else if($dataCols = $gridField->getConfig()->getComponentByType('GridFieldDataColumns')) {
@ -99,74 +127,92 @@ class GridFieldPrintButton implements GridField_HTMLProvider, GridField_ActionPr
$printColumns = singleton($gridField->getModelClass())->summaryFields(); $printColumns = singleton($gridField->getModelClass())->summaryFields();
} }
$header = null; return $printColumns;
if($this->printHasHeader){ }
$header = new ArrayList();
foreach($printColumns as $field => $label){
$header->push(
new ArrayData(array(
"CellString" => $label,
))
);
}
}
$items = $gridField->getList(); /**
foreach($gridField->getConfig()->getComponents() as $component){ * Return the title of the printed page
if($component instanceof GridFieldFilterHeader || $component instanceof GridFieldSortableHeader) { *
$items = $component->getManipulatedData($gridField, $items); * @param GridField
} *
} * @return array
*/
$items = $gridField->getManipulatedList(); public function getTitle(GridField $gridField) {
$itemRows = new ArrayList();
foreach($items as $item) {
$itemRow = new ArrayList();
foreach($printColumns as $field => $label) {
$value = $gridField->getDataFieldValue($item, $field);
$itemRow->push(
new ArrayData(array(
"CellString" => $value,
))
);
}
$itemRows->push(new ArrayData(
array(
"ItemRow" => $itemRow
)
));
$item->destroy();
}
//get title for the print view
$form = $gridField->getForm(); $form = $gridField->getForm();
$currentController = Controller::curr(); $currentController = Controller::curr();
$title = ''; $title = '';
if(method_exists($currentController, 'Title')) { if(method_exists($currentController, 'Title')) {
$title = $currentController->Title(); $title = $currentController->Title();
}else{ } else {
if($currentController->Title){ if ($currentController->Title) {
$title = $currentController->Title; $title = $currentController->Title;
}else{ } else {
if($form->Name()){ if($form->Name()){
$title = $form->Name(); $title = $form->Name();
} }
} }
} }
if($fieldTitle = $gridField->Title()){
if($title) $title .= " - "; if($fieldTitle = $gridField->Title()) {
if($title) {
$title .= " - ";
}
$title .= $fieldTitle; $title .= $fieldTitle;
} }
$ret = new ArrayData( return $title;
array( }
"Title" => $title,
"Header" => $header, /**
"ItemRows" => $itemRows, * Export core.
"Datetime" => SS_Datetime::now(), *
"Member" => Member::currentUser(), * @param GridField
) */
); public function generatePrintData(GridField $gridField) {
$printColumns = $this->getPrintColumnsForGridField($gridField);
$header = null;
if($this->printHasHeader) {
$header = new ArrayList();
foreach($printColumns as $field => $label){
$header->push(new ArrayData(array(
"CellString" => $label,
)));
}
}
$items = $gridField->getManipulatedList();
$itemRows = new ArrayList();
foreach($items as $item) {
$itemRow = new ArrayList();
foreach($printColumns as $field => $label) {
$value = $gridField->getDataFieldValue($item, $field);
$itemRow->push(new ArrayData(array(
"CellString" => $value,
)));
}
$itemRows->push(new ArrayData(array(
"ItemRow" => $itemRow
)));
$item->destroy();
}
$ret = new ArrayData(array(
"Title" => $this->getTitle($gridField),
"Header" => $header,
"ItemRows" => $itemRows,
"Datetime" => SS_Datetime::now(),
"Member" => Member::currentUser(),
));
return $ret; return $ret;
} }
@ -183,6 +229,7 @@ class GridFieldPrintButton implements GridField_HTMLProvider, GridField_ActionPr
*/ */
public function setPrintColumns($cols) { public function setPrintColumns($cols) {
$this->printColumns = $cols; $this->printColumns = $cols;
return $this; return $this;
} }
@ -198,6 +245,7 @@ class GridFieldPrintButton implements GridField_HTMLProvider, GridField_ActionPr
*/ */
public function setPrintHasHeader($bool) { public function setPrintHasHeader($bool) {
$this->printHasHeader = $bool; $this->printHasHeader = $bool;
return $this; return $this;
} }
} }

View File

@ -83,10 +83,12 @@ class GridFieldSortableHeader implements GridField_HTMLProvider, GridField_DataM
$state = $gridField->State->GridFieldSortableHeader; $state = $gridField->State->GridFieldSortableHeader;
$columns = $gridField->getColumns(); $columns = $gridField->getColumns();
$currentColumn = 0; $currentColumn = 0;
foreach($columns as $columnField) { foreach($columns as $columnField) {
$currentColumn++; $currentColumn++;
$metadata = $gridField->getColumnMetadata($columnField); $metadata = $gridField->getColumnMetadata($columnField);
$title = $metadata['title']; $title = $metadata['title'];
if(isset($this->fieldSorting[$columnField]) && $this->fieldSorting[$columnField]) { if(isset($this->fieldSorting[$columnField]) && $this->fieldSorting[$columnField]) {
$columnField = $this->fieldSorting[$columnField]; $columnField = $this->fieldSorting[$columnField];
} }

View File

@ -1,8 +1,8 @@
<?php <?php
/** /**
* This class is a snapshot of the current status of a gridfield. * This class is a snapshot of the current status of a {@link GridField}. It's
* * designed to be inserted into a Form as a HiddenField and passed through to
* It's main use is to be inserted into a Form as a HiddenField * actions such as the {@link GridField_FormAction}
* *
* @see GridField * @see GridField
* *
@ -11,23 +11,15 @@
*/ */
class GridState extends HiddenField { class GridState extends HiddenField {
/** @var GridField */ /**
* @var GridField
*/
protected $grid; protected $grid;
protected $gridStateData = null;
/** /**
* * @var GridState_Data
* @param type $d
* @return type
*/ */
public static function array_to_object($d) { protected $data = null;
if(is_array($d)) {
return (object) array_map(array('GridState', 'array_to_object'), $d);
} else {
return $d;
}
}
/** /**
* *
@ -43,40 +35,63 @@ class GridState extends HiddenField {
} }
/** /**
* * @param mixed $d
* @param type $value * @return object
*/ */
public function setValue($value) { public static function array_to_object($d) {
if (is_string($value)) { if(is_array($d)) {
$this->gridStateData = new GridState_Data(json_decode($value, true)); return (object) array_map(array('GridState', 'array_to_object'), $d);
} }
parent::setValue($value);
}
public function getData() { return $d;
if(!$this->gridStateData) $this->gridStateData = new GridState_Data;
return $this->gridStateData;
} }
/** /**
* * @param mixed $value
* @return type */
public function setValue($value) {
if (is_string($value)) {
$this->data = new GridState_Data(json_decode($value, true));
}
parent::setValue($value);
}
/**
* @var GridState_Data
*/
public function getData() {
if(!$this->data) {
$this->data = new GridState_Data();
}
return $this->data;
}
/**
* @return DataList
*/ */
public function getList() { public function getList() {
return $this->grid->getList(); return $this->grid->getList();
} }
/** @return string */ /**
* Returns a json encoded string representation of this state.
*
* @return string
*/
public function Value() { public function Value() {
if(!$this->gridStateData) { if(!$this->data) {
return json_encode(array()); return json_encode(array());
} }
return json_encode($this->gridStateData->toArray());
return json_encode($this->data->toArray());
} }
/** /**
* Returns a json encoded string representation of this state.
* *
* @return type * @return string
*/ */
public function dataValue() { public function dataValue() {
return $this->Value(); return $this->Value();
@ -100,9 +115,18 @@ class GridState extends HiddenField {
} }
/** /**
* Simple set of data, similar to stdClass, but without the notice-level errors * Simple set of data, similar to stdClass, but without the notice-level errors.
*
* @see GridState
*
* @package framework
* @subpackage fields-relational
*/ */
class GridState_Data { class GridState_Data {
/**
* @var array
*/
protected $data; protected $data;
public function __construct($data = array()) { public function __construct($data = array()) {
@ -110,42 +134,53 @@ class GridState_Data {
} }
public function __get($name) { public function __get($name) {
if(!isset($this->data[$name])) $this->data[$name] = new GridState_Data; if(!isset($this->data[$name])) {
if(is_array($this->data[$name])) $this->data[$name] = new GridState_Data($this->data[$name]); $this->data[$name] = new GridState_Data();
} else if(is_array($this->data[$name])) {
$this->data[$name] = new GridState_Data($this->data[$name]);
}
return $this->data[$name]; return $this->data[$name];
} }
public function __set($name, $value) { public function __set($name, $value) {
$this->data[$name] = $value; $this->data[$name] = $value;
} }
public function __isset($name) { public function __isset($name) {
return isset($this->data[$name]); return isset($this->data[$name]);
} }
public function __toString() { public function __toString() {
if(!$this->data) return ""; if(!$this->data) {
else return json_encode($this->toArray()); return "";
}
return json_encode($this->toArray());
} }
public function toArray() { public function toArray() {
$output = array(); $output = array();
foreach($this->data as $k => $v) { foreach($this->data as $k => $v) {
$output[$k] = (is_object($v) && method_exists($v, 'toArray')) ? $v->toArray() : $v; $output[$k] = (is_object($v) && method_exists($v, 'toArray')) ? $v->toArray() : $v;
} }
return $output; return $output;
} }
} }
/**
* @see GridState
*
* @package framework
* @subpackage fields-relational
*/
class GridState_Component implements GridField_HTMLProvider { class GridState_Component implements GridField_HTMLProvider {
public function getHTMLFragments($gridField) { public function getHTMLFragments($gridField) {
$forTemplate = new ArrayData(array());
$forTemplate->Fields = new ArrayList;
return array( return array(
'before' => $gridField->getState(false)->Field() 'before' => $gridField->getState(false)->Field()
); );
} }
} }