(merged from branches/roa. use "svn log -c <changeset> -g <module-svn-path>" for detailed commit message)

git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/cms/trunk@60207 467b73ca-7a2a-4603-9d3b-597d59a354a9
This commit is contained in:
Ingo Schommer 2008-08-09 03:54:55 +00:00
parent 83fff5f1c1
commit 2b87d00c13
8 changed files with 345 additions and 228 deletions

View File

@ -5,19 +5,20 @@
* @package cms * @package cms
*/ */
Director::addRules(50, array( Director::addRules(50, array(
'processes/$Action/$ID/$Batch' => 'BatchProcess_Controller', 'processes//$Action/$ID/$Batch' => 'BatchProcess_Controller',
'silverstripe' => '->admin', 'silverstripe' => '->admin',
'cms' => '->admin', 'cms' => '->admin',
'admin/security/$Action/$ID/$OtherID' => 'SecurityAdmin', 'admin/security//$Action/$ID/$OtherID' => 'SecurityAdmin',
'admin/help/$Action/$ID' => 'CMSHelp', 'admin/help//$Action/$ID' => 'CMSHelp',
'admin/reports/$Action/$ID' => 'ReportAdmin', 'admin/reports//$Action/$ID' => 'ReportAdmin',
'admin/assets/$Action/$ID' => 'AssetAdmin', 'admin/assets//$Action/$ID' => 'AssetAdmin',
'admin/comments/$Action' => 'CommentAdmin', 'admin/comments//$Action' => 'CommentAdmin',
'admin/ReportField/$Action/$ID/$Type/$OtherID' => 'ReportField_Controller', 'admin/ReportField//$Action/$ID/$Type/$OtherID' => 'ReportField_Controller',
'admin/ImageEditor/$Action' => 'ImageEditor', 'admin/bulkload//$Action/$ID/$OtherID' => 'BulkLoaderAdmin',
'admin/$Action/$ID/$OtherID' => 'CMSMain', 'admin//ImageEditor/$Action' => 'ImageEditor',
'unsubscribe/$Email/$MailingList' => 'Unsubscribe_Controller', 'admin//$Action/$ID/$OtherID' => 'CMSMain',
'PageComment/$Action/$ID' => 'PageComment_Controller' 'unsubscribe//$Email/$MailingList' => 'Unsubscribe_Controller'
'PageComment//$Action/$ID' => 'PageComment_Controller'
)); ));
// Built-in modules // Built-in modules

View File

@ -43,6 +43,8 @@ class CMSMain extends LeftAndMain implements CurrentPageIdentifier, PermissionPr
'unpublish', 'unpublish',
'versions', 'versions',
'waitingon', 'waitingon',
'EditForm',
'AddPageOptionsForm',
); );
/** /**

View File

@ -35,6 +35,7 @@ class LeftAndMain extends Controller {
'printable', 'printable',
'save', 'save',
'show', 'show',
'Member_ProfileForm'
); );
/** /**

View File

@ -39,7 +39,16 @@ abstract class ModelAdmin extends LeftAndMain {
public static $allowed_actions = array( public static $allowed_actions = array(
'add', 'add',
'edit', 'edit',
'delete' 'delete',
'handleList',
'handleItem'
);
/**
* Forward control to the default action handler
*/
public static $url_handlers = array(
'$Action' => 'handleAction'
); );
/** /**
@ -49,15 +58,17 @@ abstract class ModelAdmin extends LeftAndMain {
* @var string * @var string
*/ */
private $currentModel = false; private $currentModel = false;
/** /**
* Initialize the model admin interface. Sets up embedded jquery libraries and requisite plugins * Initialize the model admin interface. Sets up embedded jquery libraries and requisite plugins.
*
* @todo remove reliance on urlParams
*/ */
public function init() { public function init() {
parent::init(); parent::init();
// security check for valid models // security check for valid models
if(isset($this->urlParams['Model']) && !in_array($this->urlParams['Model'], $this->getManagedModels())) { if(isset($this->urlParams['Action']) && !in_array($this->urlParams['Action'], $this->getManagedModels())) {
user_error('ModelAdmin::init(): Invalid Model class', E_USER_ERROR); user_error('ModelAdmin::init(): Invalid Model class', E_USER_ERROR);
} }
@ -77,15 +88,14 @@ abstract class ModelAdmin extends LeftAndMain {
*/ */
function defineMethods() { function defineMethods() {
parent::defineMethods(); parent::defineMethods();
foreach($this->getManagedModels() as $class) { foreach($this->getManagedModels() as $ClassName) {
$this->addWrapperMethod('SearchForm_' . $class, 'getSearchFormForModel'); $this->addWrapperMethod($ClassName, 'bindModelController');
$this->addWrapperMethod('AddForm_' . $class, 'getAddFormForModel');
$this->addWrapperMethod('EditForm_' . $class, 'getEditFormForModel');
} }
} }
/** /**
* Return default link to this controller * Return default link to this controller. This assfaced method is abstract, so we can't
* get rid of it.
* *
* @todo extract full URL binding from Director::addRules so that it's not tied to 'admin/crm' * @todo extract full URL binding from Director::addRules so that it's not tied to 'admin/crm'
* @todo is there a way of removing the dependency on this method from the Form? * @todo is there a way of removing the dependency on this method from the Form?
@ -93,41 +103,14 @@ abstract class ModelAdmin extends LeftAndMain {
* @return string * @return string
*/ */
public function Link() { public function Link() {
return 'admin/crm/' . implode('/', array_values(array_unique($this->urlParams))); return Controller::join_links(Director::absoluteBaseURL(), 'admin/crm/');
} }
/** /**
* Create empty edit form (scaffolded from DataObject->getCMSFields() by default). * Base scaffolding method for returning a generic model instance.
* Can be called either through {@link AddForm()} or directly through URL:
* "/myadminroute/add/MyModelClass"
*/ */
public function add($data) { public function bindModelController($model, $request = null) {
$className = (isset($data['ClassName'])) ? $data['ClassName'] : $this->urlParams['ClassName']; return new ModelAdmin_CollectionController($this, $model);
if(!isset($className) || !in_array($data['ClassName'], $this->getManagedModels())) return false;
$form = $this->getEditForm($data['ClassName']);
return $form->forTemplate();
}
/**
* Edit forms (scaffolded from DataObject->getCMSFields() by default).
*
* @param array $data
* @param Form $form
*/
public function edit($data, $form) {
if(!isset($data['ClassName']) || !in_array($data['ClassName'], $this->getManagedModels())) return false;
// @todo generate editform
}
/**
*
* @param array $data
*/
public function save($data, $form) {
Debug::dump($data);
} }
/** /**
@ -135,14 +118,14 @@ abstract class ModelAdmin extends LeftAndMain {
* *
* @return Form * @return Form
*/ */
protected function AddForm() { protected function ManagedModelsSelect() {
$models = $this->getManagedModels(); $models = $this->getManagedModels();
$modelMap = array(); $modelMap = array();
foreach($models as $modelName) $modelMap[$modelName] = singleton($modelName)->singular_name(); foreach($models as $modelName) $modelMap[$modelName] = singleton($modelName)->singular_name();
$form = new Form( $form = new Form(
$this, $this,
"AddForm", "ManagedModelsSelect",
new FieldSet( new FieldSet(
new DropdownField('ClassName', 'Type', $modelMap) new DropdownField('ClassName', 'Type', $modelMap)
), ),
@ -154,6 +137,11 @@ abstract class ModelAdmin extends LeftAndMain {
return $form; return $form;
} }
function add($data, $form, $request) {
$className = $request->requestVar("ClassName");
return $this->$className()->add($request);
}
/** /**
* *
* @uses {@link SearchContext} * @uses {@link SearchContext}
@ -165,41 +153,18 @@ abstract class ModelAdmin extends LeftAndMain {
$forms = new DataObjectSet(); $forms = new DataObjectSet();
foreach($modelClasses as $modelClass) { foreach($modelClasses as $modelClass) {
$modelObj = singleton($modelClass); $this->$modelClass()->SearchForm();
$form = $this->getSearchFormForModel($modelClass);
$forms->push(new ArrayData(array( $forms->push(new ArrayData(array(
'Form' => $form, 'Form' => $this->$modelClass()->SearchForm(),
'Title' => $modelObj->singular_name() 'Title' => singleton($modelClass)->singular_name(),
'ClassName' => $modelClass,
))); )));
} }
return $forms; return $forms;
} }
/**
* Enter description here...
*
* @todo Add customizeable validator
*
* @param string $modelClass
*/
protected function getEditForm($modelClass) {
$modelObj = singleton($modelClass);
$formName = "EditForm_$modelClass";
$fields = $this->getFieldsForModel($modelObj);
$this->getComponentFieldsForModel($modelObj, $fields);
$actions = $this->getActionsForModel($modelObj);
$validator = $this->getValidatorForModel($modelObj);
// necessary because of overriding the form action - NEED TO VERIFY THIS
$fields->push(new HiddenField("executeForm", $formName));
$form = new Form($this, $formName, $fields, $actions, $validator);
return $form;
}
// ############# Utility Methods ##############
/** /**
* @return array * @return array
*/ */
@ -210,164 +175,271 @@ abstract class ModelAdmin extends LeftAndMain {
return $models; return $models;
} }
}
/**
* Handles a managed model class and provides default collection filtering behavior.
*
*/
class ModelAdmin_CollectionController extends Controller {
protected $parentController;
protected $modelClass;
/** static $url_handlers = array(
* Get all cms fields for the model '$Action' => 'handleActionOrID'
* (defaults to {@link DataObject->getCMSFields()}). );
*
* @todo Make method hook customizeable function __construct($parent, $model) {
* $this->parentController = $parent;
* @param DataObject $modelObj $this->modelClass = $model;
* @return FieldSet
*/
protected function getFieldsForModel($modelObj) {
$fields = $modelObj->getCMSFields();
if (!$fields->dataFieldByName('ID')) {
$fields->push(new HiddenField('ID'));
}
return $fields;
} }
/** /**
* Update: complex table field generation moved into controller - could be * Appends the model class to the URL.
* in the DataObject scaffolding?
* *
* @param unknown_type $modelObj * @return unknown
* @return FieldSet of ComplexTableFields
*/ */
protected function getComponentFieldsForModel($modelObj, $fieldSet) { function Link() {
foreach($modelObj->has_many() as $relationship => $component) { return Controller::join_links($this->parentController->Link(), "$this->modelClass");
}
$relationshipFields = array_keys(singleton($component)->searchableFields());
$fieldSet->push(new ComplexTableField($this, $relationship, $component, $relationshipFields)); /**
* Return the class name of the model being managed.
*
* @return unknown
*/
function getModelClass() {
return $this->modelClass;
}
/**
* Smashes a massive whole in the Law of Demeter.
*
* http://en.wikipedia.org/wiki/Law_of_Demeter
*/
/* I've commented this out because it's not actually used anymore
function getParentController() {
return $this->parentController;
}
*/
/**
* Delegate to different control flow, depending on whether the
* URL parameter is a numeric type (record id) or string (action).
*
* @param unknown_type $request
* @return unknown
*/
function handleActionOrID($request) {
if (is_numeric($request->param('Action'))) {
return $this->handleID($request);
} else {
return $this->handleAction($request);
} }
return $fieldSet;
} }
/** /**
* Get all actions which are possible in this controller, * Delegate to the RecordController if a valid numeric ID appears in the URL
* and allowed by the model security. * segment.
* *
* @todo Hook into model security once its is implemented * @param HTTPRequest $request
* * @return RecordController
* @param DataObject $modelObj
* @return FieldSet
*/ */
protected function getActionsForModel($modelObj) { function handleID($request) {
$actions = new FieldSet( return new ModelAdmin_RecordController($this, $request);
new FormAction('save', _t('GenericDataAdmin.SAVE')),
new FormAction('delete', _t('GenericDataAdmin.DELETE'))
);
return $actions;
} }
/** /////////////////////////////////////////////////////////////////////////////////////////////////////////
* NOT IMPLEMENTED
* Get a valdidator for the model.
*
* @todo Hook into model security once its is implemented
*
* @param DataObject $modelObj
* @return FieldSet
*/
protected function getValidatorForModel($modelObj) {
return false;
}
/** /**
* Get a search form for a single {@link DataObject} subclass. * Get a search form for a single {@link DataObject} subclass.
* *
* @param string $modelClass * @return Form
* @return FieldSet
*/ */
protected function getSearchFormForModel($modelClass) { public function SearchForm() {
if(substr($modelClass,0,11) == 'SearchForm_') $modelClass = substr($modelClass, 11); $context = singleton($this->modelClass)->getDefaultSearchContext();
$context = singleton($modelClass)->getDefaultSearchContext(); $form = new Form($this, "SearchForm",
$form = new Form(
$this,
"SearchForm_$modelClass",
$context->getSearchFields(), $context->getSearchFields(),
new FieldSet( new FieldSet(
new FormAction('search', _t('MemberTableField.SEARCH')) new FormAction('search', _t('MemberTableField.SEARCH'))
) )
); );
$form->setFormAction(Controller::join_links($this->Link(), "search"));
$form->setFormMethod('get'); $form->setFormMethod('get');
$form->setHTMLID("Form_SearchForm_" . $this->modelClass);
return $form; return $form;
} }
/**
* Overwrite the default form action with the path to the DataObject filter
* (relies on the search form having the specifically named id as 'SearchForm_DataObject')
*
* @todo override default linking to add DataObject based URI paths
*/
function FormObjectLink($formName) {
return $this->Link();
}
/** /**
* Action to render a data object collection, using the model context to provide filters * Action to render a data object collection, using the model context to provide filters
* and paging. * and paging.
*
* @todo push this HTML structure out into separate template
*/ */
function search($data, $form) { function search($request) {
$className = $this->urlParams['ClassName']; $model = singleton($this->modelClass);
Debug::dump($className); $searchKeys = array_intersect_key($request->getVars(), $model->searchableFields());
if (in_array($className, $this->getManagedModels())) { $context = $model->getDefaultSearchContext();
$model = singleton($className); $results = $context->getResultSet($searchKeys);
// @todo need to filter post vars $output = "";
$searchKeys = array_intersect_key($_POST, $model->searchableFields()); if ($results) {
$context = $model->getDefaultSearchContext(); $output .= "<table>";
$results = $context->getResultSet($searchKeys); foreach($results as $row) {
if ($results) { $uri = Director::absoluteBaseUrl();
echo "<table>"; $output .= "<tr title=\"{$uri}admin/crm/{$this->modelClass}/{$row->ID}/edit\">";
foreach($results as $row) { foreach($model->searchableFields() as $key=>$val) {
$uri = Director::absoluteBaseUrl(); $output .= "<td>";
echo "<tr id=\"{$uri}admin/crm/view/$className/$row->ID\">"; $output .= $row->getField($key);
foreach($model->searchableFields() as $key=>$val) { $output .= "</td>";
echo "<td>";
echo $row->getField($key);
echo "</td>";
}
echo "</tr>";
} }
echo "</table>"; $output .= "</tr>";
} else {
echo "<p>No results found</p>";
} }
$output .= "</table>";
} else {
$output .= "<p>No results found</p>";
} }
die(); return $output;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Create a new model record.
*
* @param unknown_type $request
* @return unknown
*/
function add($request) {
return $this->AddForm()->forTemplate();
}
/**
* Returns a form for editing the attached model
*/
public function AddForm() {
$newRecord = new $this->modelClass();
$fields = $newRecord->getCMSFields();
$validator = ($newRecord->hasMethod('getCMSValidator')) ? $newRecord->getCMSValidator() : null;
$actions = new FieldSet(new FormAction("doCreate", "Add"));
$form = new Form($this, "AddForm", $fields, $actions, $validator);
return $form;
}
function doCreate($data, $form, $request) {
$className = $this->getModelClass();
$model = new $className();
$form->saveInto($model);
$model->write();
Director::redirect(Controller::join_links($this->Link(), $model->ID , 'edit'));
}
}
/**
* Handles operations on a single record from a managed model.
*
* @todo change the parent controller varname to indicate the model scaffolding functionality in ModelAdmin
*/
class ModelAdmin_RecordController extends Controller {
protected $parentController;
protected $currentRecord;
static $allowed_actions = array('edit', 'view', 'EditForm', 'ViewForm');
function __construct($parentController, $request) {
$this->parentController = $parentController;
$modelName = $parentController->getModelClass();
$recordID = $request->param('Action');
$this->currentRecord = DataObject::get_by_id($modelName, $recordID);
} }
/** /**
* View a generic model using a form object to render a partial HTML * Link fragment - appends the current record ID to the URL.
* fragment to be embedded via Ajax calls. *
*/ */
function show() { function Link() {
$className = $this->urlParams['ClassName']; return Controller::join_links($this->parentController->Link(), "/{$this->currentRecord->ID}");
$ID = $this->urlParams['ID']; }
if (in_array($className, $this->getManagedModels())) { /////////////////////////////////////////////////////////////////////////////////////////////////////////
$model = DataObject::get_by_id($className, $ID); /**
* Edit action - shows a form for editing this record
/*$fields = $model->getCMSFields(); */
function edit($request) {
$actions = new FieldSet( if ($this->currentRecord) {
new FormAction('save', 'Save') return $this->EditForm()->forTemplate();
); } else {
return "I can't find that item";
$form = new Form($this, $className, $fields, $actions);
$form->makeReadonly();*/
$form = $this->getEditForm($className);
$form->loadNonBlankDataFrom($model);
return $form->forTemplate();
} }
} }
/**
* Returns a form for editing the attached model
*/
public function EditForm() {
$fields = $this->currentRecord->getCMSFields();
$fields->push(new HiddenField("ID"));
$validator = ($this->currentRecord->hasMethod('getCMSValidator')) ? $this->currentRecord->getCMSValidator() : null;
$actions = new FieldSet(new FormAction("doSave", "Save"));
$form = new Form($this, "EditForm", $fields, $actions, $validator);
$form->loadDataFrom($this->currentRecord);
return $form;
}
function doSave($data, $form, $request) {
$this->currentRecord->update($request->postVars());
$this->currentRecord->write();
// Behaviour switched on ajax.
if(Director::is_ajax()) {
return $this->edit($request);
} else {
Director::redirectBack();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @todo remove base controller hack and refactor scaffolding methods to be better distributed in class heirachy
*/
function view($request) {
if ($this->currentRecord) {
$form = $this->ViewForm();
return $form->forTemplate();
} else {
return "I can't find that item";
}
}
/**
* Returns a form for viewing the attached model
*/
public function ViewForm() {
$fields = $this->currentRecord->getCMSFields();
$form = new Form($this, "EditForm", $fields, new FieldSet());
$form->loadDataFrom($this->currentRecord);
$form->makeReadonly();
return $form;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
function index() {
Director::redirect(Controller::join_links($this->Link(), 'edit'));
}
} }
?> ?>

View File

@ -17,6 +17,8 @@ class SecurityAdmin extends LeftAndMain implements PermissionProvider {
'newmember', 'newmember',
'removememberfromgroup', 'removememberfromgroup',
'savemember', 'savemember',
'AddRecordForm',
'MemberForm'
); );
public function init() { public function init() {

View File

@ -1,47 +1,86 @@
/**
* Javascript handlers for generic model admin.
*
* Most of the work being done here is intercepting clicks on form submits,
* and managing the loading and sequencing of data between the different panels of
* the CMS interface.
*
* @todo add live query to manage application of events to DOM refreshes
* @todo alias the $ function instead of literal jQuery
*/
jQuery(document).ready(function() { jQuery(document).ready(function() {
/**
* GET a fragment of HTML to display in the right panel
*/
function showRecord(uri) { function showRecord(uri) {
jQuery.get(uri, function(result){ jQuery.get(uri, function(result){
jQuery('#right').html(result); jQuery('#right').html(result);
Behaviour.apply(); Behaviour.apply(); // refreshes ComplexTableField
}); });
} }
/**
* POST a hash of form submitted data to the given endpoint
*/
function saveRecord(uri, data) { function saveRecord(uri, data) {
//jQuery.post(uri, data, function(result) {) jQuery.post(uri, data, function(result){
jQuery('#right').html(result);
});
} }
jQuery('#AddForm_holder form').submit(function(){ /**
className = jQuery('select option:selected', this).val(); * Returns a flattened array of data from each field
// @todo remove dependency on hardcoded URL path * of the given form
requestPath = jQuery(this).attr('action') + '/add/' + className; */
showRecord(requestPath); function formData(scope) {
return false;
});
// attach generic action handler to all forms displayed in the #right panel
jQuery('#right .action').click(function(){
alert('do something here');
return false;
});
jQuery('#SearchForm_holder').tabs();
jQuery('.tab form').submit(function(){
form = jQuery(this);
var data = {}; var data = {};
jQuery('*[name]', form).each(function(){ jQuery('*[name]', scope).each(function(){
var t = jQuery(this); var t = jQuery(this);
var val = (t.attr('type') == 'checkbox') ? (t.attr('checked') == true) ? 1 : 0 : t.val(); var val = (t.attr('type') == 'checkbox') ? (t.attr('checked') == true) ? 1 : 0 : t.val();
data[t.attr('name')] = val; data[t.attr('name')] = val;
}); });
return data;
}
/**
* Find the selected data object and load its create form
*/
jQuery('#AddForm_holder form').submit(function(){
className = jQuery('select option:selected', this).val();
requestPath = jQuery(this).attr('action').replace('ManagedModelsSelect', className + '/add');
showRecord(requestPath);
return false;
});
/**
* attach generic action handler to all forms displayed in the #right panel
*/
jQuery('#right .action').livequery('click', function(){
form = jQuery('#right form');
saveRecord(form.attr('action'), formData(form));
return false;
});
/**
* Attach tabs plugin to the set of search filter forms
*/
jQuery('#SearchForm_holder').tabs();
/**
* Submits a search filter query and attaches event handlers
* to the response table
*
* @todo use livequery to manage ResultTable click handlers
*/
jQuery('.tab form').submit(function(){
form = jQuery(this);
data = formData(form);
jQuery.get(form.attr('action'), data, function(result){ jQuery.get(form.attr('action'), data, function(result){
jQuery('#ResultTable_holder').html(result); jQuery('#ResultTable_holder').html(result);
jQuery('#ResultTable_holder td').click(function(){ jQuery('#ResultTable_holder td').click(function(){
td = jQuery(this); td = jQuery(this);
showRecord(td.parent().attr('id')); showRecord(td.parent().attr('title'));
td.parent().parent().find('td').removeClass('active'); td.parent().parent().find('td').removeClass('active');
td.addClass('active').siblings().addClass('active'); td.addClass('active').siblings().addClass('active');
}).hover(function(){ }).hover(function(){

View File

View File

@ -1,17 +1,17 @@
<div id="LeftPane"> <div id="LeftPane">
<h2><% _t('ADDLISTING','Add Listing') %></h2> <h2><% _t('ADDLISTING','Add Listing') %></h2>
<div id="AddForm_holder" class="lefttop"> <div id="AddForm_holder" class="lefttop">
$AddForm $ManagedModelsSelect
</div> </div>
<h2><% _t('SEARCHLISTINGS','Search Listings') %></h2> <h2><% _t('SEARCHLISTINGS','Search Listings') %></h2>
<div id="SearchForm_holder" class="leftbottom"> <div id="SearchForm_holder" class="leftbottom">
<ul class="tabstrip"> <ul class="tabstrip">
<% control SearchForms %> <% control SearchForms %>
<li class="first"><a href="#$Form.Name">$Title</a></li> <li class="first"><a href="#{$Form.Name}_$ClassName">$Title</a></li>
<% end_control %> <% end_control %>
</ul> </ul>
<% control SearchForms %> <% control SearchForms %>
<div class="tab" id="$Form.Name"> <div class="tab" id="{$Form.Name}_$ClassName">
$Form $Form
</div> </div>
<% end_control %> <% end_control %>