/**
  * Updates the form to make all of the fields read only with the exception of a few fields
  * @param {Form} $form Form to be adjusted
  */
 public function updateEditForm(Form $form)
 {
     $record = $form->getRecord();
     if ($record) {
         $kapostRefID = $record->KapostRefID;
         if (empty($kapostRefID)) {
             return;
         }
         //Make the fields all read only
         $oldFields = $form->Fields();
         $form->setFields($oldFields->makeReadonly());
         //Make the fields that should be non-readonly editable again
         foreach ($record->config()->non_readonly_fields as $fieldName) {
             $oldField = $oldFields->dataFieldByName($fieldName);
             if ($oldField) {
                 $form->Fields()->replaceField($fieldName, $oldField);
             }
         }
         //Loop through the wysiwyg fields that need to be made safe and sanitize their html
         foreach ($record->config()->make_safe_wysiwyg_fields as $fieldName) {
             $field = $form->Fields()->dataFieldByName($fieldName);
             if ($field) {
                 $field->setName($field->getName() . '_safe');
                 $field->setValue($this->sanitizeHTML($field->Value()));
             }
         }
     }
 }
 function getEditForm($id = null)
 {
     if (!$id) {
         $id = $this->currentPageID();
     }
     if ($id && $id != 'root') {
         $record = DataObject::get_by_id($this->stat('tree_class'), $id);
         if (!$record) {
             return false;
         }
     }
     if ($id && is_numeric($id)) {
         $fields = $record->getCMSFields();
         if ($fields->hasTabSet()) {
             // Add import capabilities. Limit to admin since the import logic can affect assigned permissions
             if (Permission::check('ADMIN')) {
                 $fields->findOrMakeTab('Root.Import', _t('Group.IMPORTTABTITLE', 'Import'));
                 $fields->addFieldToTab('Root.Import', new LiteralField('MemberImportFormIframe', sprintf('<iframe src="%s" id="MemberImportFormIframe" width="100%%" height="400px" border="0"></iframe>', $this->Link('memberimport'))));
             }
             if (Permission::check('APPLY_ROLES')) {
                 $fields->addFieldToTab('Root.Roles', new LiteralField('RolesAddEditLink', sprintf('<p class="add-role"><a href="%s">%s</a></p>', $this->Link('show/root'), _t('Group.RolesAddEditLink', 'Add/edit roles'))));
             }
         }
         $actions = new FieldSet(new FormAction('addmember', _t('SecurityAdmin.ADDMEMBER', 'Add Member')), new FormAction('save', _t('SecurityAdmin.SAVE', 'Save')));
         $form = new Form($this, "EditForm", $fields, $actions);
         $form->loadDataFrom($record);
         if (!$record->canEdit()) {
             $readonlyFields = $form->Fields()->makeReadonly();
             $form->setFields($readonlyFields);
         }
         // Filter permissions
         $permissionField = $form->Fields()->dataFieldByName('Permissions');
         if ($permissionField) {
             $permissionField->setHiddenPermissions(self::$hidden_permissions);
         }
         $this->extend('updateEditForm', $form);
     } else {
         $form = $this->RootForm();
     }
     return $form;
 }
 /**
  * Updates the form to make all of the fields read only with the exception of a few fields
  * @param {Form} $form Form to be adjusted
  */
 public function updateEditForm(Form $form)
 {
     $record = $form->getRecord();
     if ($record) {
         $kapostRefID = $record->KapostRefID;
         if (empty($kapostRefID)) {
             return;
         }
         //Make the fields all read only
         $oldFields = $form->Fields();
         $form->setFields($oldFields->makeReadonly());
         //Make the fields that should be non-readonly editable again
         if (is_array($record->config()->non_readonly_settings_fields)) {
             foreach ($record->config()->non_readonly_settings_fields as $fieldName) {
                 $oldField = $oldFields->dataFieldByName($fieldName);
                 if ($oldField) {
                     $form->Fields()->replaceField($fieldName, $oldField);
                 }
             }
         }
     }
 }
 /**
  * @param Int $id
  * @param FieldList $fields
  * @return Form
  */
 public function getEditForm($id = null, $fields = null)
 {
     if (!$id) {
         $id = $this->currentPageID();
     }
     $form = parent::getEditForm($id);
     // TODO Duplicate record fetching (see parent implementation)
     $record = $this->getRecord($id);
     if ($record && !$record->canView()) {
         return Security::permissionFailure($this);
     }
     if (!$fields) {
         $fields = $form->Fields();
     }
     $actions = $form->Actions();
     if ($record) {
         $deletedFromStage = $record->IsDeletedFromStage;
         $deleteFromLive = !$record->ExistsOnLive;
         $fields->push($idField = new HiddenField("ID", false, $id));
         // Necessary for different subsites
         $fields->push($liveLinkField = new HiddenField("AbsoluteLink", false, $record->AbsoluteLink()));
         $fields->push($liveLinkField = new HiddenField("LiveLink"));
         $fields->push($stageLinkField = new HiddenField("StageLink"));
         if ($record->ID && is_numeric($record->ID)) {
             $liveLink = $record->getAbsoluteLiveLink();
             if ($liveLink) {
                 $liveLinkField->setValue($liveLink);
             }
             if (!$deletedFromStage) {
                 $stageLink = Controller::join_links($record->AbsoluteLink(), '?stage=Stage');
                 if ($stageLink) {
                     $stageLinkField->setValue($stageLink);
                 }
             }
         }
         // Added in-line to the form, but plucked into different view by LeftAndMain.Preview.js upon load
         /*if(in_array('CMSPreviewable', class_implements($record)) && !$fields->fieldByName('SilverStripeNavigator')) {
         			$navField = new LiteralField('SilverStripeNavigator', $this->getSilverStripeNavigator());
         			$navField->setAllowHTML(true);
         			$fields->push($navField);
         		}*/
         // getAllCMSActions can be used to completely redefine the action list
         if ($record->hasMethod('getAllCMSActions')) {
             $actions = $record->getAllCMSActions();
         } else {
             $actions = $record->getCMSActions();
         }
         // Use <button> to allow full jQuery UI styling
         $actionsFlattened = $actions->dataFields();
         if ($actionsFlattened) {
             foreach ($actionsFlattened as $action) {
                 $action->setUseButtonTag(true);
             }
         }
         if ($record->hasMethod('getCMSValidator')) {
             $validator = $record->getCMSValidator();
         } else {
             $validator = new RequiredFields();
         }
         $form = new Form($this, "EditForm", $fields, $actions, $validator);
         $form->loadDataFrom($record);
         $form->disableDefaultAction();
         $form->addExtraClass('cms-edit-form content-module');
         $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
         // TODO Can't merge $FormAttributes in template at the moment
         $form->addExtraClass('center ' . $this->BaseCSSClasses());
         $form->setAttribute('data-pjax-fragment', 'CurrentForm');
         if (!$record->canEdit() || $deletedFromStage) {
             $readonlyFields = $form->Fields()->makeReadonly();
             $form->setFields($readonlyFields);
         }
         $this->extend('updateEditForm', $form);
         return $form;
     } else {
         if ($id) {
             return new Form($this, "EditForm", new FieldList(new LabelField('ModuleDoesntExistLabel', _t('ContentModule.MODULENOTEXISTS', "This module doesn't exist"))), new FieldList());
         }
     }
     return $this->ListViewForm();
 }
Example #5
0
 /**
  * Calls {@link SiteTree->getCMSFields()}
  * 
  * @param Int $id
  * @param FieldList $fields
  * @return Form
  */
 public function getEditForm($id = null, $fields = null)
 {
     if (!$id) {
         $id = $this->currentPageID();
     }
     if (is_object($id)) {
         $record = $id;
     } else {
         $record = $this->getRecord($id);
         if ($record && !$record->canView()) {
             return Security::permissionFailure($this);
         }
     }
     if ($record) {
         $fields = $fields ? $fields : $record->getCMSFields();
         if ($fields == null) {
             user_error("getCMSFields() returned null  - it should return a FieldList object. \n\t\t\t\t\tPerhaps you forgot to put a return statement at the end of your method?", E_USER_ERROR);
         }
         // Add hidden fields which are required for saving the record
         // and loading the UI state
         if (!$fields->dataFieldByName('ClassName')) {
             $fields->push(new HiddenField('ClassName'));
         }
         if (Object::has_extension($this->stat('tree_class'), 'Hierarchy') && !$fields->dataFieldByName('ParentID')) {
             $fields->push(new HiddenField('ParentID'));
         }
         // Added in-line to the form, but plucked into different view by LeftAndMain.Preview.js upon load
         if (in_array('CMSPreviewable', class_implements($record))) {
             $navField = new LiteralField('SilverStripeNavigator', $this->getSilverStripeNavigator());
             $navField->setAllowHTML(true);
             $fields->push($navField);
         }
         if ($record->hasMethod('getAllCMSActions')) {
             $actions = $record->getAllCMSActions();
         } else {
             $actions = $record->getCMSActions();
             // add default actions if none are defined
             if (!$actions || !$actions->Count()) {
                 if ($record->hasMethod('canEdit') && $record->canEdit()) {
                     $actions->push(FormAction::create('save', _t('CMSMain.SAVE', 'Save'))->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept'));
                 }
                 if ($record->hasMethod('canDelete') && $record->canDelete()) {
                     $actions->push(FormAction::create('delete', _t('ModelAdmin.DELETE', 'Delete'))->addExtraClass('ss-ui-action-destructive'));
                 }
             }
         }
         // Use <button> to allow full jQuery UI styling
         $actionsFlattened = $actions->dataFields();
         if ($actionsFlattened) {
             foreach ($actionsFlattened as $action) {
                 $action->setUseButtonTag(true);
             }
         }
         $form = new Form($this, "EditForm", $fields, $actions);
         $form->addExtraClass('cms-edit-form');
         $form->loadDataFrom($record);
         $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
         $form->setAttribute('data-pjax-fragment', 'CurrentForm');
         // Set this if you want to split up tabs into a separate header row
         // if($form->Fields()->hasTabset()) $form->Fields()->findOrMakeTab('Root')->setTemplate('CMSTabSet');
         // Add a default or custom validator.
         // @todo Currently the default Validator.js implementation
         //  adds javascript to the document body, meaning it won't
         //  be included properly if the associated fields are loaded
         //  through ajax. This means only serverside validation
         //  will kick in for pages+validation loaded through ajax.
         //  This will be solved by using less obtrusive javascript validation
         //  in the future, see http://open.silverstripe.com/ticket/2915 and
         //  http://open.silverstripe.com/ticket/3386
         if ($record->hasMethod('getCMSValidator')) {
             $validator = $record->getCMSValidator();
             // The clientside (mainly LeftAndMain*.js) rely on ajax responses
             // which can be evaluated as javascript, hence we need
             // to override any global changes to the validation handler.
             $form->setValidator($validator);
         } else {
             $form->unsetValidator();
         }
         if ($record->hasMethod('canEdit') && !$record->canEdit()) {
             $readonlyFields = $form->Fields()->makeReadonly();
             $form->setFields($readonlyFields);
         }
     } else {
         $form = $this->EmptyForm();
     }
     return $form;
 }
 public function getEditForm($id = null)
 {
     if (!$id) {
         $id = $this->currentPageID();
     }
     $record = $id && $id != "root" ? $this->getRecord($id) : null;
     if ($record && !$record->canView()) {
         return Security::permissionFailure($this);
     }
     if ($record) {
         $fields = $record->getCMSFields();
         if ($fields == null) {
             user_error("getCMSFields() returned null  - it should return a FieldSet object. \n\t\t\t\t\tPerhaps you forgot to put a return statement at the end of your method?", E_USER_ERROR);
         }
         // Add hidden fields which are required for saving the record
         // and loading the UI state
         if (!$fields->dataFieldByName('ClassName')) {
             $fields->push(new HiddenField('ClassName'));
         }
         if (Object::has_extension($this->stat('tree_class'), 'Hierarchy') && !$fields->dataFieldByName('ParentID')) {
             $fields->push(new HiddenField('ParentID'));
         }
         if ($record->hasMethod('getAllCMSActions')) {
             $actions = $record->getAllCMSActions();
         } else {
             $actions = $record->getCMSActions();
             // add default actions if none are defined
             if (!$actions || !$actions->Count()) {
                 if ($record->canEdit()) {
                     $actions->push(new FormAction('save', _t('CMSMain.SAVE', 'Save')));
                 }
             }
         }
         $form = new Form($this, "EditForm", $fields, $actions);
         $form->loadDataFrom($record);
         // Add a default or custom validator.
         // @todo Currently the default Validator.js implementation
         //  adds javascript to the document body, meaning it won't
         //  be included properly if the associated fields are loaded
         //  through ajax. This means only serverside validation
         //  will kick in for pages+validation loaded through ajax.
         //  This will be solved by using less obtrusive javascript validation
         //  in the future, see http://open.silverstripe.com/ticket/2915 and
         //  http://open.silverstripe.com/ticket/3386
         if ($record->hasMethod('getCMSValidator')) {
             $validator = $record->getCMSValidator();
             // The clientside (mainly LeftAndMain*.js) rely on ajax responses
             // which can be evaluated as javascript, hence we need
             // to override any global changes to the validation handler.
             $validator->setJavascriptValidationHandler('prototype');
             $form->setValidator($validator);
         } else {
             $form->unsetValidator();
         }
         if (!$record->canEdit()) {
             $readonlyFields = $form->Fields()->makeReadonly();
             $form->setFields($readonlyFields);
         }
     } else {
         $form = $this->RootForm();
     }
     return $form;
 }
 function compareversions()
 {
     $id = (int) $this->urlParams['ID'];
     $version1 = (int) $_REQUEST['From'];
     $version2 = (int) $_REQUEST['To'];
     if ($version1 > $version2) {
         $toVersion = $version1;
         $fromVersion = $version2;
     } else {
         $toVersion = $version2;
         $fromVersion = $version1;
     }
     $page = DataObject::get_by_id("SiteTree", $id);
     if ($page && !$page->canView()) {
         return Security::permissionFailure($this);
     }
     $record = $page->compareVersions($fromVersion, $toVersion);
     $fromVersionRecord = Versioned::get_version('SiteTree', $id, $fromVersion);
     $toVersionRecord = Versioned::get_version('SiteTree', $id, $toVersion);
     if (!$fromVersionRecord) {
         user_error("Can't find version {$fromVersion} of page {$id}", E_USER_ERROR);
     }
     if (!$toVersionRecord) {
         user_error("Can't find version {$toVersion} of page {$id}", E_USER_ERROR);
     }
     if ($record) {
         $fromDateNice = $fromVersionRecord->obj('LastEdited')->Ago();
         $toDateNice = $toVersionRecord->obj('LastEdited')->Ago();
         $fromAuthor = DataObject::get_by_id('Member', $fromVersionRecord->AuthorID);
         if (!$fromAuthor) {
             $fromAuthor = new ArrayData(array('Title' => 'Unknown author'));
         }
         $toAuthor = DataObject::get_by_id('Member', $toVersionRecord->AuthorID);
         if (!$toAuthor) {
             $toAuthor = new ArrayData(array('Title' => 'Unknown author'));
         }
         $fields = $record->getCMSFields($this);
         $fields->push(new HiddenField("ID"));
         $fields->push(new HiddenField("Version"));
         $fields->insertBefore(new LiteralField('YouAreComparingHeader', '<p class="message notice">' . sprintf(_t('CMSMain.COMPARINGV', "Comparing versions %s and %s"), "<a href=\"admin/getversion/{$id}/{$fromVersionRecord->Version}\" title=\"{$fromAuthor->Title}\">{$fromVersionRecord->Version}</a> <small>({$fromDateNice})</small>", "<a href=\"admin/getversion/{$id}/{$toVersionRecord->Version}\" title=\"{$toAuthor->Title}\">{$toVersionRecord->Version}</a> <small>({$toDateNice})</small>") . '</p>'), "Root");
         $actions = new FieldSet();
         $form = new Form($this, "EditForm", $fields, $actions);
         $form->loadDataFrom($record);
         $form->loadDataFrom(array("ID" => $id, "Version" => $fromVersion));
         // comparison views shouldn't be editable
         $readonlyFields = $form->Fields()->makeReadonly();
         $form->setFields($readonlyFields);
         foreach ($form->Fields()->dataFields() as $field) {
             $field->dontEscape = true;
         }
         return $this->sendFormToBrowser(array("EditForm" => $form));
     }
 }
 /**
  * Calls {@link DataObject->getCMSFields()}
  *
  * @param Int $id
  * @param FieldList $fields
  * @return Form
  */
 public function ItemEditForm($id = null, $fields = null)
 {
     if ($this->record) {
         $className = $this->getItemClassName();
         $record = null;
         if ($id && is_numeric($id)) {
             $record = DataObject::get_by_id($className, (int) $id);
         } else {
             if (!empty($_REQUEST['RecordID'])) {
                 $record = DataObject::get_by_id($className, (int) $_REQUEST['RecordID']);
             } else {
                 if (!empty($_REQUEST['ID'])) {
                     $record = DataObject::get_by_id($className, (int) $_REQUEST['ID']);
                 } else {
                     if ($this->_idField) {
                         $record = DataObject::get_by_id($className, (int) $this->_idField);
                     } else {
                         if ($id = $this->getSessionID()) {
                             $record = DataObject::get_by_id($className, $id);
                         }
                     }
                 }
             }
         }
         if (!$record) {
             $record = new $className();
         }
         $fields = $fields ? $fields : $record->getCMSFields();
         if ($fields == null) {
             user_error("getCMSFields() returned null  - it should return a FieldList object.\n                                        Perhaps you forgot to put a return statement at the end of your method?", E_USER_ERROR);
         }
         if ($record->hasMethod('getAllCMSActions')) {
             $actions = $record->getAllCMSActions();
         } else {
             $actions = $record->getCMSActions();
             // add default actions if none are defined
             if (!$actions || !$actions->Count()) {
                 if ($record->hasMethod('canEdit') && $record->canEdit()) {
                     $actions->push(FormAction::create('save', _t('CMSMain.SAVE', 'Save'))->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept'));
                 }
                 if ($record->hasMethod('canDelete') && $record->canDelete() && $record->exists()) {
                     $actions->push(FormAction::create('delete', _t('ModelAdmin.DELETE', 'Delete'))->addExtraClass('ss-ui-action-destructive'));
                 }
             }
         }
         // Use <button> to allow full jQuery UI styling
         $actionsFlattened = $actions->dataFields();
         if ($actionsFlattened) {
             foreach ($actionsFlattened as $action) {
                 $action->setUseButtonTag(true);
             }
         }
         $form = new Form($this, "ItemEditForm", $fields, $actions);
         $form->addExtraClass('cms-edit-form ContentRelationshipEditor_Form');
         $form->setAttribute('data-pjax-fragment', 'CurrentForm');
         // Set this if you want to split up tabs into a separate header row
         // if($form->Fields()->hasTabset()) {
         // 	$form->Fields()->findOrMakeTab('Root')->setTemplate('CMSTabSet');
         // }
         // Add a default or custom validator.
         // @todo Currently the default Validator.js implementation
         //  adds javascript to the document body, meaning it won't
         //  be included properly if the associated fields are loaded
         //  through ajax. This means only serverside validation
         //  will kick in for pages+validation loaded through ajax.
         //  This will be solved by using less obtrusive javascript validation
         //  in the future, see http://open.silverstripe.com/ticket/2915 and
         //  http://open.silverstripe.com/ticket/3386
         if ($record->hasMethod('getCMSValidator')) {
             $validator = $record->getCMSValidator();
             // The clientside (mainly LeftAndMain*.js) rely on ajax responses
             // which can be evaluated as javascript, hence we need
             // to override any global changes to the validation handler.
             $form->setValidator($validator);
         } else {
             $form->unsetValidator();
         }
         if ($record->hasMethod('canEdit') && !$record->canEdit()) {
             $readonlyFields = $form->Fields()->makeReadonly();
             $form->setFields($readonlyFields);
         }
         if ($record->exists()) {
             //rename to recordID so it doesn't conflict with CMSMain/LeftAndMain
             $fields->push(new HiddenField('RecordID', 'RecordID', $record->ID));
             //store in session so we can use for subfields
             $this->setSessionID($record->ID);
         }
         $form->loadDataFrom($record);
         //echo $form->getRecord()->ID;exit;
         $form->setFormAction($this->Link('ItemEditForm'));
         return $form;
     }
     return false;
 }
 public function getMemberForm($id)
 {
     if ($id && $id != 'new') {
         $record = DataObject::get_by_id('Member', (int) $id);
     }
     if ($record || $id == 'new') {
         $fields = new FieldSet(new HiddenField('MemberListBaseGroup', '', $this->currentPageID()));
         if ($extraFields = $record->getCMSFields()) {
             foreach ($extraFields as $extra) {
                 $fields->push($extra);
             }
         }
         $fields->push($idField = new HiddenField('ID'));
         $fields->push($groupIDField = new HiddenField('GroupID'));
         $actions = new FieldSet();
         $actions->push(new FormAction('savemember', _t('SecurityAdmin.SAVE', 'Save')));
         $form = new Form($this, 'MemberForm', $fields, $actions);
         if ($record) {
             $form->loadDataFrom($record);
         }
         $idField->setValue($id);
         $groupIDField->setValue($this->currentPageID());
         if ($record && !$record->canEdit()) {
             $readonlyFields = $form->Fields()->makeReadonly();
             $form->setFields($readonlyFields);
         }
         return $form;
     }
 }
 /**
  * Handles actually adding a folder to the databsae
  * @param {array} $data Submitted data
  * @param {Form} $form Submitting form
  * @return {string} HTML to be rendered
  */
 public function doAddFolder($data, Form $form)
 {
     //Existing Check
     $existingCheck = SnippetFolder::get()->filter('Name:nocase', Convert::raw2sql($data['Name']))->filter('LanguageID', intval($data['LanguageID']));
     if (array_key_exists('FolderID', $data)) {
         $existingCheck = $existingCheck->filter('ParentID', intval($data['FolderID']));
     } else {
         $existingCheck->filter('ParentID', 0);
     }
     if ($existingCheck->Count() > 0) {
         $form->sessionMessage(_t('CodeBank.FOLDER_EXISTS', '_A folder already exists with that name'), 'bad');
         return $this->redirectBack();
     }
     $folder = new SnippetFolder();
     $folder->Name = $data['Name'];
     $folder->LanguageID = $data['LanguageID'];
     if (array_key_exists('ParentID', $data)) {
         $folder->ParentID = $data['ParentID'];
     }
     //Write the folder to the database
     $folder->write();
     //Find the next & previous nodes, for proper positioning (Sort isn't good enough - it's not a raw offset)
     $next = $prev = null;
     $next = SnippetFolder::get()->filter('LanguageID', $folder->LanguageID)->filter('ParentID', $folder->ParentID)->filter('Name:GreaterThan', Convert::raw2sql($folder->Title))->first();
     if (!$next) {
         $prev = SnippetFolder::get()->filter('LanguageID', $folder->LanguageID)->filter('ParentID', $folder->ParentID)->filter('Name:LessThan', Convert::raw2sql($folder->Title))->reverse()->first();
     }
     //Setup js that will add the node to the tree
     $html = CodeBank_TreeNode::create($folder, '', false)->forTemplate() . '</li>';
     $parentFolder = $folder->Parent();
     $outputData = array('folder-' . $folder->ID => array('html' => $html, 'ParentID' => !empty($parentFolder) && $parentFolder !== false && $parentFolder->ID != 0 ? 'folder-' . $folder->ParentID : 'language-' . $folder->LanguageID, 'NextID' => $next ? 'folder-' . $next->ID : null, 'PrevID' => $prev ? 'folder-' . $prev->ID : null));
     Requirements::customScript('window.parent.updateCodeBankTreeNodes(' . json_encode($outputData) . ');');
     //Re-render the form
     $form->setFields(new FieldList());
     $form->setActions(new FieldList());
     $form->setMessage(_t('CodeBank.FOLDER_ADDED', '_Folder added you may now close this dialog'), 'good');
     return $this->customise(array('Content' => ' ', 'Form' => $form))->renderWith('CMSDialog');
 }
 /**
  * creates a form object with a free configurable markup
  *
  * @param ContentController $controller  the calling controller instance
  * @param array             $params      optional parameters
  * @param array             $preferences optional preferences
  * @param bool              $barebone    defines if a form should only be instanciated or be used too
  *
  * @return CustomHtmlForm
  *
  * @author Sebastian Diel <*****@*****.**>,
  *         Sascha Koehler <*****@*****.**>
  * @since 13.01.2015
  */
 public function __construct($controller, $params = null, $preferences = null, $barebone = false)
 {
     $this->extend('onBeforeConstruct', $controller, $params, $preferences, $barebone);
     global $project;
     $this->barebone = $barebone;
     $this->controller = $controller;
     if (is_array($params)) {
         $this->customParameters = $params;
     }
     // Hook for setting preferences via a method call
     $this->preferences();
     if (is_array($preferences)) {
         foreach ($preferences as $title => $setting) {
             if (!empty($title)) {
                 $this->basePreferences[$title] = $setting;
             }
         }
     }
     $name = $this->getSubmitAction();
     if (!$barebone) {
         $this->getFormFields();
     }
     if ($this->securityTokenEnabled) {
         SecurityToken::enable();
     } else {
         SecurityToken::disable();
     }
     parent::__construct($this->getFormController($controller, $preferences), $name, new FieldList(), new FieldList());
     if (!$barebone) {
         $this->getFormFields();
         $this->fillInFieldValues();
     }
     // Hook for setting preferences via a method call; we need to do this
     // a second time so that the standard Silverstripe mechanism can take
     // influence, too (i.e. _config.php files, init methods, etc).
     $this->preferences();
     if (is_array($preferences)) {
         foreach ($preferences as $title => $setting) {
             if (!empty($title)) {
                 $this->basePreferences[$title] = $setting;
             }
         }
     }
     // Counter for the form class, init or increment
     if (!isset(self::$classInstanceCounter[$this->class])) {
         self::$classInstanceCounter[$this->class] = 0;
     }
     if (!$barebone) {
         self::$classInstanceCounter[$this->class]++;
     }
     // new assignment required, because the controller will be overwritten in the form class
     $this->controller = $controller;
     // create group structure
     if (isset($this->formFields)) {
         $this->fieldGroups['formFields'] = $this->getFormFields();
     } else {
         $this->fieldGroups['formFields'] = array();
     }
     $this->name = str_replace('/', '', $this->class . '_' . $name . '_' . self::$classInstanceCounter[$this->class]);
     $this->jsName = $this->name;
     $this->SSformFields = $this->getForm();
     $this->SSformFields['fields']->setForm($this);
     $this->SSformFields['actions']->setForm($this);
     parent::setFields($this->SSformFields['fields']);
     parent::setActions($this->SSformFields['actions']);
     // define form action
     $this->setFormAction($this->buildFormAction());
     $this->setHTMLID($this->getName());
     /*
      * load and init JS validators
      * form integration via FormAttributes()
      */
     if (!$barebone) {
         $javascriptSnippets = $this->getJavascriptValidatorInitialisation();
         if (!$this->getLoadShoppingCartModules()) {
             SilvercartShoppingCart::setLoadShoppingCartModules(false);
         }
         if ($this->getCreateShoppingCartForms() && class_exists('SilvercartShoppingCart')) {
             SilvercartShoppingCart::setCreateShoppingCartForms(false);
         }
         $this->controller->addJavascriptSnippet($javascriptSnippets['javascriptSnippets']);
         $this->controller->addJavascriptOnloadSnippet($javascriptSnippets['javascriptOnloadSnippets']);
         $this->controller->addJavascriptOnloadSnippet($this->getJavascriptFieldInitialisations());
     }
     // Register the default module directory from mysite/_config.php
     self::registerModule($project);
     $this->extend('onAfterConstruct', $controller, $params, $preferences, $barebone);
 }
Example #12
0
 function compareversions()
 {
     $id = $this->request->param('ID') ? $this->request->param('ID') : $this->request->requestVar('ID');
     $versions = $this->request->requestVar('Versions');
     $version1 = $versions && isset($versions[0]) ? $versions[0] : $this->request->getVar('From');
     $version2 = $versions && isset($versions[1]) ? $versions[1] : $this->request->getVar('To');
     if ($version1 > $version2) {
         $toVersion = $version1;
         $fromVersion = $version2;
     } else {
         $toVersion = $version2;
         $fromVersion = $version1;
     }
     if (!$toVersion || !$toVersion) {
         return false;
     }
     $page = DataObject::get_by_id("SiteTree", $id);
     if ($page && !$page->canView()) {
         return Security::permissionFailure($this);
     }
     $record = $page->compareVersions($fromVersion, $toVersion);
     $fromVersionRecord = Versioned::get_version('SiteTree', $id, $fromVersion);
     $toVersionRecord = Versioned::get_version('SiteTree', $id, $toVersion);
     if (!$fromVersionRecord) {
         user_error("Can't find version {$fromVersion} of page {$id}", E_USER_ERROR);
     }
     if (!$toVersionRecord) {
         user_error("Can't find version {$toVersion} of page {$id}", E_USER_ERROR);
     }
     if ($record) {
         $fromDateNice = $fromVersionRecord->obj('LastEdited')->Ago();
         $toDateNice = $toVersionRecord->obj('LastEdited')->Ago();
         $fromAuthor = DataObject::get_by_id('Member', $fromVersionRecord->AuthorID);
         if (!$fromAuthor) {
             $fromAuthor = new ArrayData(array('Title' => 'Unknown author'));
         }
         $toAuthor = DataObject::get_by_id('Member', $toVersionRecord->AuthorID);
         if (!$toAuthor) {
             $toAuthor = new ArrayData(array('Title' => 'Unknown author'));
         }
         $fields = $record->getCMSFields($this);
         $fields->push(new HiddenField("ID"));
         $fields->push(new HiddenField("Version"));
         $fields->insertBefore(new LiteralField('YouAreComparingHeader', '<p class="message notice">' . sprintf(_t('CMSMain.COMPARINGV', "Comparing versions %s and %s"), "<a href=\"admin/getversion/{$id}/{$fromVersionRecord->Version}\" title=\"{$fromAuthor->Title}\">{$fromVersionRecord->Version}</a> <small>({$fromDateNice})</small>", "<a href=\"admin/getversion/{$id}/{$toVersionRecord->Version}\" title=\"{$toAuthor->Title}\">{$toVersionRecord->Version}</a> <small>({$toDateNice})</small>") . '</p>'), "Root");
         $actions = new FieldSet();
         $form = new Form($this, "EditForm", $fields, $actions);
         $form->loadDataFrom($record);
         $form->loadDataFrom(array("ID" => $id, "Version" => $fromVersion));
         $form->addExtraClass('compare');
         // comparison views shouldn't be editable
         $readonlyFields = $form->Fields()->makeReadonly();
         $form->setFields($readonlyFields);
         foreach ($form->Fields()->dataFields() as $field) {
             $field->dontEscape = true;
         }
         if ($this->isAjax()) {
             return $form->formHtmlContent();
         } else {
             $templateData = $this->customise(array("EditForm" => $form));
             return $templateData->renderWith('LeftAndMain');
         }
     }
 }
 public function getNewsletterEditForm($myId)
 {
     $email = DataObject::get_by_id("Newsletter", $myId);
     if ($email) {
         $fields = $email->getCMSFields($this);
         $fields->push($idField = new HiddenField("ID"));
         $idField->setValue($myId);
         $fields->push($ParentidField = new HiddenField("ParentID"));
         $ParentidField->setValue($email->ParentID);
         $fields->push($typeField = new HiddenField("Type"));
         $typeField->setValue('Newsletter');
         //$fields->push(new HiddenField("executeForm", "", "EditForm") );
         $actions = new FieldSet();
         if ($email->SentDate) {
             $actions->push(new FormAction('send', _t('NewsletterAdmin.RESEND', 'Resend')));
         } else {
             $actions->push(new FormAction('send', _t('NewsletterAdmin.SEND', 'Send...')));
         }
         $actions->push(new FormAction('save', _t('NewsletterAdmin.SAVE', 'Save')));
         $form = new Form($this, "NewsletterEditForm", $fields, $actions);
         $form->loadDataFrom($email);
         // This saves us from having to change all the JS in response to renaming this form to NewsletterEditForm
         $form->setHTMLID('Form_EditForm');
         if ($email->Status != 'Draft') {
             $readonlyFields = $form->Fields()->makeReadonly();
             $form->setFields($readonlyFields);
         }
         // user_error( $form->FormAction(), E_USER_ERROR );
         return $form;
     } else {
         user_error('Unknown Email ID: ' . $myId, E_USER_ERROR);
     }
 }
 /**
  * Post a comment form
  *
  * @return Form
  */
 public function CommentsForm()
 {
     $member = Member::currentUser();
     $fields = new FieldList(new TextField("Name", _t('CommentInterface.YOURNAME', 'Your name')), new EmailField("Email", _t('CommentingController.EMAILADDRESS', "Your email address (will not be published)")), new TextField("URL", _t('CommentingController.WEBSITEURL', "Your website URL")), new TextareaField("Comment", _t('CommentingController.COMMENTS', "Comments")), new HiddenField("ParentID"), new HiddenField("ReturnURL"), new HiddenField("BaseClass"));
     // save actions
     $actions = new FieldList(new FormAction("doPostComment", _t('CommentInterface.POST', 'Post')));
     // required fields for server side
     $required = new RequiredFields(array('Name', 'Email', 'Comment'));
     // create the comment form
     $form = new Form($this, 'CommentsForm', $fields, $actions, $required);
     // if the record exists load the extra required data
     if ($record = $this->getOwnerRecord()) {
         $require_login = Commenting::get_config_value($this->getBaseClass(), 'require_login');
         $permission = Commenting::get_config_value($this->getBaseClass(), 'required_permission');
         if (($require_login || $permission) && $member) {
             $fields = $form->Fields();
             $fields->removeByName('Name');
             $fields->removeByName('Email');
             $fields->insertBefore(new ReadonlyField("NameView", _t('CommentInterface.YOURNAME', 'Your name'), $member->getName()), 'URL');
             $fields->push(new HiddenField("Name", "", $member->getName()));
             $fields->push(new HiddenField("Email", "", $member->Email));
             $form->setFields($fields);
         }
         // we do not want to read a new URL when the form has already been submitted
         // which in here, it hasn't been.
         $url = isset($_SERVER['REQUEST_URI']) ? Director::protocolAndHost() . '' . $_SERVER['REQUEST_URI'] : false;
         $form->loadDataFrom(array('ParentID' => $record->ID, 'ReturnURL' => $url, 'BaseClass' => $this->getBaseClass()));
     }
     // Set it so the user gets redirected back down to the form upon form fail
     $form->setRedirectToFormOnValidationError(true);
     // load any data from the cookies
     if ($data = Cookie::get('CommentsForm_UserData')) {
         $data = Convert::json2array($data);
         $form->loadDataFrom(array("Name" => isset($data['Name']) ? $data['Name'] : '', "URL" => isset($data['URL']) ? $data['URL'] : '', "Email" => isset($data['Email']) ? $data['Email'] : '', "Comment" => Cookie::get('CommentsForm_Comment')));
     }
     if ($member) {
         $form->loadDataFrom($member);
     }
     // hook to allow further extensions to alter the comments form
     $this->extend('alterCommentForm', $form);
     return $form;
 }
 /**
  * @param DataObjectInterface $record
  */
 public function saveInto(DataObjectInterface $record)
 {
     if ($this->isDisabled() || $this->isReadonly()) {
         return;
     }
     $name = $this->name;
     $idName = $name . "ID";
     $widgetarea = $record->getComponent($name);
     $widgetarea->write();
     $record->{$idName} = $widgetarea->ID;
     $widgets = $widgetarea->Items();
     // store the field IDs and delete the missing fields
     // alternatively, we could delete all the fields and re add them
     $missingWidgets = array();
     if ($widgets) {
         foreach ($widgets as $existingWidget) {
             $missingWidgets[$existingWidget->ID] = $existingWidget;
         }
     }
     if (isset($_REQUEST['Widget'])) {
         foreach (array_keys($_REQUEST['Widget']) as $widgetAreaName) {
             if ($widgetAreaName !== $this->name) {
                 continue;
             }
             $widgetForm = new Form($this, 'WidgetForm', new FieldList(), new FieldList());
             foreach (array_keys($_REQUEST['Widget'][$widgetAreaName]) as $newWidgetID) {
                 $newWidgetData = $_REQUEST['Widget'][$widgetAreaName][$newWidgetID];
                 // Sometimes the id is "new-1" or similar, ensure this doesn't get into the query
                 if (!is_numeric($newWidgetID)) {
                     $newWidgetID = 0;
                 }
                 // \"ParentID\" = '0' is for the new page
                 $widget = DataObject::get_one('Widget', "(\"ParentID\"='{$record->{$name}()->ID}' OR " . "\"ParentID\"='0') AND \"Widget\".\"ID\"='{$newWidgetID}'");
                 // check if we are updating an existing widget
                 if ($widget && isset($missingWidgets[$widget->ID])) {
                     unset($missingWidgets[$widget->ID]);
                 }
                 // create a new object
                 if (!$widget && !empty($newWidgetData['Type']) && class_exists($newWidgetData['Type'])) {
                     $widget = new $newWidgetData['Type']();
                     $widget->ID = 0;
                     $widget->ParentID = $record->{$name}()->ID;
                     if (!is_subclass_of($widget, 'Widget')) {
                         $widget = null;
                     }
                 }
                 if ($widget) {
                     if ($widget->ParentID == 0) {
                         $widget->ParentID = $record->{$name}()->ID;
                     }
                     //Set the widget editor
                     $widget->setWidgetEditor($this);
                     //Set the form's fields
                     $widgetForm->setFields($widget->getCMSFields());
                     //Populate the form
                     $widgetForm->loadDataFrom($newWidgetData);
                     //Save the form into the widget and write
                     $widgetForm->saveInto($widget);
                     $widget->Sort = array_key_exists('Sort', $newWidgetData) ? $newWidgetData['Sort'] : $widget->Sort;
                     $widget->write();
                 }
             }
         }
     }
     // remove the fields not saved
     if ($missingWidgets) {
         foreach ($missingWidgets as $removedWidget) {
             if (isset($removedWidget) && is_numeric($removedWidget->ID)) {
                 $removedWidget->delete();
             }
         }
     }
 }
 public function getNewsletterEditForm($myId)
 {
     $email = DataObject::get_by_id("Newsletter", $myId);
     if ($email) {
         $fields = $email->getCMSFields($this);
         $actions = $email->getCMSActions();
         $fields->push($idField = new HiddenField("ID"));
         $idField->setValue($myId);
         $fields->push($ParentidField = new HiddenField("ParentID"));
         $ParentidField->setValue($email->ParentID);
         $fields->push($typeField = new HiddenField("Type"));
         $typeField->setValue('Newsletter');
         $form = new Form($this, "NewsletterEditForm", $fields, $actions);
         $form->loadDataFrom($email);
         // This saves us from having to change all the JS in response to renaming this form to NewsletterEditForm
         $form->setHTMLID('Form_EditForm');
         if ($email->Status != 'Draft') {
             $readonlyFields = $form->Fields()->makeReadonly();
             $form->setFields($readonlyFields);
         }
         $this->extend('updateEditForm', $form);
         return $form;
     } else {
         user_error('Unknown Email ID: ' . $myId, E_USER_ERROR);
     }
 }