/**
  * @param int|null $id
  * @param array|null $fields
  * @return \Form
  */
 public function getEditForm($id = null, $fields = null)
 {
     $queues = $this->getQueues();
     $gridField = new GridField('Queues', 'Queues', $queues, new GridFieldConfig_RecordEditor());
     $dataComponent = $gridField->getConfig()->getComponentByType('GridFieldDataColumns');
     $dataComponent->setDisplayFields(array('Name' => 'Name', 'Size' => 'Size'));
     $form = new Form($this, 'EditForm', new FieldList($gridField), new FieldList());
     $form->addExtraClass('cms-edit-form cms-panel-padded center');
     $form->setAttribute('data-pjax-fragment', 'CurrentForm');
     $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
     $form->setAttribute('data-pjax-fragment', 'CurrentForm');
     return $form;
 }
 /**
  * returns the form
  * @return Form
  */
 public function getGoogleSiteSearchForm($name = "GoogleSiteSearchForm")
 {
     $formIDinHTML = "Form_" . $name;
     if ($page = GoogleCustomSearchPage::get()->first()) {
         Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
         Requirements::javascript('googlecustomsearch/javascript/GoogleCustomSearch.js');
         $apiKey = Config::inst()->get("GoogleCustomSearchExt", "api_key");
         $cxKey = Config::inst()->get("GoogleCustomSearchExt", "cx_key");
         if ($apiKey && $cxKey) {
             Requirements::customScript("\n\t\t\t\t\t\tGoogleCustomSearch.apiKey = '" . $apiKey . "';\n\t\t\t\t\t\tGoogleCustomSearch.cxKey = '" . $cxKey . "';\n\t\t\t\t\t\tGoogleCustomSearch.formSelector = '#" . $formIDinHTML . "';\n\t\t\t\t\t\tGoogleCustomSearch.inputFieldSelector = '#" . $formIDinHTML . "_search';\n\t\t\t\t\t\tGoogleCustomSearch.resultsSelector = '#" . $formIDinHTML . "_Results';\n\t\t\t\t\t", "GoogleCustomSearchExt");
             $form = new Form($this->owner, 'GoogleSiteSearchForm', new FieldList($searchField = new TextField('search'), $resultField = new LiteralField($name . "_Results", "<div id=\"" . $formIDinHTML . "_Results\"></div>")), new FieldList(new FormAction('doSearch', _t("GoogleCustomSearchExt.GO", "Full Results"))));
             $form->setFormMethod('GET');
             if ($page = GoogleCustomSearchPage::get()->first()) {
                 $form->setFormAction($page->Link());
             }
             $form->disableSecurityToken();
             $form->loadDataFrom($_GET);
             $searchField->setAttribute("autocomplete", "off");
             $form->setAttribute("autocomplete", "off");
             return $form;
         } else {
             user_error("You must set an API Key and a CX key in your configs to use the Google Custom Search Form", E_USER_NOTICE);
         }
     } else {
         user_error("You must create a GoogleCustomSearchPage first.", E_USER_NOTICE);
     }
 }
 public function getEditForm($id = null, $fields = null)
 {
     $classname = $this->modelClass;
     $list = $classname::get();
     $listField = GridField::create($this->sanitiseClassName($this->modelClass), false, $list, $fieldConfig = GridFieldConfig_RecordEditor::create($this->stat('page_length'))->removeComponentsByType('GridFieldFilterHeader'));
     if (!$this->stat('enable_sorting')) {
         $summary_fields = Config::inst()->get($this->modelClass, 'summary_fields');
         $sorting = array();
         foreach ($summary_fields as $col) {
             $sorting[$col] = 'FieldNameNoSorting';
         }
         $fieldConfig->getComponentByType('GridFieldSortableHeader')->setFieldSorting($sorting);
     }
     // Validation
     if (singleton($this->modelClass)->hasMethod('getCMSValidator')) {
         $detailValidator = singleton($this->modelClass)->getCMSValidator();
         $listField->getConfig()->getComponentByType('GridFieldDetailForm')->setValidator($detailValidator);
     }
     $form = new Form($this, 'EditForm', new FieldList($listField), new FieldList());
     $form->addExtraClass('cms-edit-form cms-panel-padded center');
     $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
     $editFormAction = Controller::join_links($this->Link($this->sanitiseClassName($this->modelClass)), 'EditForm');
     $form->setFormAction($editFormAction);
     $form->setAttribute('data-pjax-fragment', 'CurrentForm');
     $this->extend('updateEditForm', $form);
     return $form;
 }
 /**
  * @return Form
  */
 public function AddForm()
 {
     $fields = new FieldList(new LiteralField('SelectFieldType', '<p><strong>Please select a field type to add:</strong></p>'), $df = new DropdownField('ClassName', '', $this->getFieldTypes(), null, null));
     $df->setHasEmptyDefault(true);
     if ($schemaID = (int) $this->request->param('ID')) {
         $fields->push(new HiddenField('SchemaID', '', $schemaID));
     }
     $actions = new FieldList(FormAction::create('doAddField', 'Create')->setUseButtonTag(true)->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept'));
     // Add a Cancel link which is a button-like link and link back to one level up.
     $curmbs = $this->Breadcrumbs();
     if ($curmbs && $curmbs->count() >= 2) {
         $one_level_up = $curmbs->offsetGet($curmbs->count() - 2);
         $text = "\n\t\t\t<a class=\"crumb ss-ui-button ss-ui-action-destructive cms-panel-link ui-corner-all\" href=\"" . $one_level_up->Link . "\">\n\t\t\t\tCancel\n\t\t\t</a>";
         $actions->push(new LiteralField('cancelbutton', $text));
     }
     $form = new Form($this, 'AddForm', $fields, $actions);
     $toplevelController = $this->getToplevelController();
     $form->setTemplate('LeftAndMain_EditForm');
     $form->addExtraClass('cms-content cms-edit-form center ss-tabset stacked');
     $form->setAttribute('data-pjax-fragment', 'CurrentForm Content');
     if ($form->Fields()->hasTabset()) {
         $form->Fields()->findOrMakeTab('Root')->setTemplate('CMSTabSet');
     }
     //var_dump($this->popupController); die;
     $parents = $this->popupController->Breadcrumbs(false)->items;
     $form->Backlink = array_pop($parents)->Link;
     return $form;
 }
 public function index()
 {
     $user = System::getUser();
     $form = new Form('form-profile');
     $form->setAttribute('data-noajax', 'true');
     $form->binding = $user;
     $fieldset = new Fieldset(System::getLanguage()->_('General'));
     $firstname = new Text('firstname', System::getLanguage()->_('Firstname'));
     $firstname->binding = new Databinding('firstname');
     $lastname = new Text('lastname', System::getLanguage()->_('Lastname'));
     $lastname->binding = new Databinding('lastname');
     $email = new Text('email', System::getLanguage()->_('EMail'), true);
     $email->binding = new Databinding('email');
     $email->blacklist = $this->getListOfMailAdresses($user);
     $email->error_msg[4] = System::getLanguage()->_('ErrorMailAdressAlreadyExists');
     $language = new Radiobox('lang', System::getLanguage()->_('Language'), L10N::getLanguages());
     $language->binding = new Databinding('lang');
     $fieldset->addElements($firstname, $lastname, $email, $language);
     $form->addElements($fieldset);
     $fieldset = new Fieldset(System::getLanguage()->_('Password'));
     $password = new Password('password', System::getLanguage()->_('Password'));
     $password->minlength = PASSWORD_MIN_LENGTH;
     $password->binding = new Databinding('password');
     $password2 = new Password('password2', System::getLanguage()->_('ReenterPassword'));
     $fieldset->addElements($password, $password2);
     $form->addElements($fieldset);
     $fieldset = new Fieldset(System::getLanguage()->_('Settings'));
     $quota = new Text('quota', System::getLanguage()->_('Quota'));
     if ($user->quota > 0) {
         $quota->value = System::getLanguage()->_('QuotaAvailabe', Utils::formatBytes($user->getFreeSpace()), Utils::formatBytes($user->quota));
     } else {
         $quota->value = System::getLanguage()->_('Unlimited');
     }
     $quota->readonly = true;
     $fieldset->addElements($quota);
     $form->addElements($fieldset);
     if (Utils::getPOST('submit', false) !== false) {
         if (!empty($password->value) && $password->value != $password2->value) {
             $password2->error = System::getLanguage()->_('ErrorInvalidPasswords');
         } else {
             if ($form->validate()) {
                 $form->save();
                 System::getUser()->save();
                 System::getSession()->setData('successMsg', System::getLanguage()->_('ProfileUpdated'));
                 System::forwardToRoute(Router::getInstance()->build('ProfileController', 'index'));
                 exit;
             }
         }
     } else {
         $form->fill();
     }
     $form->setSubmit(new Button(System::getLanguage()->_('Save'), 'floppy-disk'));
     $smarty = new Template();
     $smarty->assign('title', System::getLanguage()->_('MyProfile'));
     $smarty->assign('heading', System::getLanguage()->_('MyProfile'));
     $smarty->assign('form', $form->__toString());
     $smarty->display('form.tpl');
 }
Example #6
0
 /**
  * Builds an item edit form.  The arguments to getCMSFields() are the popupController and
  * popupFormName, however this is an experimental API and may change.
  * 
  * @todo In the future, we will probably need to come up with a tigher object representing a partially
  * complete controller with gaps for extra functionality.  This, for example, would be a better way
  * of letting Security/login put its log-in form inside a UI specified elsewhere.
  * 
  * @return Form 
  */
 function ItemEditForm()
 {
     if (empty($this->record)) {
         $controller = Controller::curr();
         $noActionURL = $controller->removeAction($_REQUEST['url']);
         $controller->getResponse()->removeHeader('Location');
         //clear the existing redirect
         return $controller->redirect($noActionURL, 302);
     }
     $actions = new FieldList();
     if ($this->record->ID !== 0) {
         $actions->push(FormAction::create('doSave', _t('GridFieldDetailForm.Save', 'Save'))->setUseButtonTag(true)->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept'));
         $actions->push(FormAction::create('doDelete', _t('GridFieldDetailForm.Delete', 'Delete'))->addExtraClass('ss-ui-action-destructive'));
     } else {
         // adding new record
         //Change the Save label to 'Create'
         $actions->push(FormAction::create('doSave', _t('GridFieldDetailForm.Create', 'Create'))->setUseButtonTag(true)->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'add'));
         // Add a Cancel link which is a button-like link and link back to one level up.
         $curmbs = $this->Breadcrumbs();
         if ($curmbs && $curmbs->count() >= 2) {
             $one_level_up = $curmbs->offsetGet($curmbs->count() - 2);
             $cancelText = _t('GridFieldDetailForm.CancelBtn', 'Cancel');
             $text = "\r\n\t\t\t\t<a class=\"crumb ss-ui-button ss-ui-action-destructive cms-panel-link ui-corner-all\" href=\"" . $one_level_up->Link . "\">\r\n\t\t\t\t\t{$cancelText}\r\n\t\t\t\t</a>";
             $actions->push(new LiteralField('cancelbutton', $text));
         }
     }
     $fk = $this->gridField->getList()->foreignKey;
     $this->record->{$fk} = $this->gridField->getList()->foreignID;
     $form = new Form($this, 'ItemEditForm', $this->record->getCMSFields(), $actions, $this->component->getValidator());
     $form->loadDataFrom($this->record);
     // TODO Coupling with CMS
     $toplevelController = $this->getToplevelController();
     if ($toplevelController && $toplevelController instanceof LeftAndMain) {
         // Always show with base template (full width, no other panels),
         // regardless of overloaded CMS controller templates.
         // TODO Allow customization, e.g. to display an edit form alongside a search form from the CMS controller
         $form->setTemplate('LeftAndMain_EditForm');
         $form->addExtraClass('cms-content cms-edit-form center ss-tabset');
         $form->setAttribute('data-pjax-fragment', 'CurrentForm Content');
         if ($form->Fields()->hasTabset()) {
             $form->Fields()->findOrMakeTab('Root')->setTemplate('CMSTabSet');
         }
         if ($toplevelController->hasMethod('Backlink')) {
             $form->Backlink = $toplevelController->Backlink();
         } elseif ($this->popupController->hasMethod('Breadcrumbs')) {
             $parents = $this->popupController->Breadcrumbs(false)->items;
             $form->Backlink = array_pop($parents)->Link;
         } else {
             $form->Backlink = $toplevelController->Link();
         }
     }
     $cb = $this->component->getItemEditFormCallback();
     if ($cb) {
         $cb($form, $this);
     }
     return $form;
 }
 /**
  * This method should be overloaded to build out the detail form.
  *
  * @return Form
  */
 public function Form()
 {
     $form = new Form($this, 'Form', new FieldList($root = new TabSet('Root', new Tab('Main'))), new FieldList());
     if ($this->getTopLevelController() instanceof LeftAndMain) {
         $form->setTemplate('LeftAndMain_EditForm');
         $form->addExtraClass('cms-content cms-edit-form cms-tabset center');
         $form->setAttribute('data-pjax-fragment', 'CurrentForm Content');
         $root->setTemplate('CMSTabSet');
         $form->Backlink = $this->getBackLink();
     }
     return $form;
 }
 public function GenerateCouponsForm()
 {
     $fields = Object::create('OrderCoupon')->getCMSFields();
     $fields->removeByName('Code');
     $fields->removeByName('GiftVoucherID');
     $fields->removeByName('SaveNote');
     $fields->addFieldsToTab("Root.Main", array(NumericField::create('Number', 'Number of Coupons'), FieldGroup::create("Code", TextField::create("Prefix", "Code Prefix")->setMaxLength(5), DropdownField::create("Length", "Code Characters Length", array_combine(range(5, 20), range(5, 20)), OrderCoupon::config()->generated_code_length)->setDescription("This is in addition to the length of the prefix."))), "Title");
     $actions = new FieldList(new FormAction('generate', 'Generate'));
     $validator = new RequiredFields(array('Title', 'Number', 'Type'));
     $form = new Form($this, "GenerateCouponsForm", $fields, $actions, $validator);
     $form->addExtraClass("cms-edit-form cms-panel-padded center ui-tabs-panel ui-widget-content ui-corner-bottom");
     $form->setAttribute('data-pjax-fragment', 'CurrentForm');
     $form->setHTMLID('Form_EditForm');
     $form->loadDataFrom(array('Number' => 1, 'Active' => 1, 'ForCart' => 1, 'UseLimit' => 1));
     return $form;
 }
 /**
  * Get search form
  *
  * @return Form
  */
 public function BlogSearchForm()
 {
     $searchField = TextField::create('Keyword', false)->setAttribute('placeholder', 'Type to search')->setAttribute('type', 'search');
     $keyword = Controller::curr()->request->getVar('Search');
     if ($keyword) {
         $searchField->setValue($keyword);
     }
     $fields = new FieldList($searchField);
     $formAction = FormAction::create('doSearch');
     $formAction->useButtonTag = true;
     $formAction->setButtonContent('<span class="fa fa-search"></span>');
     $actions = new FieldList($formAction);
     $form = new Form($this, 'BlogSearchForm', $fields, $actions);
     $form->setAttribute('role', 'search');
     $form->setTemplate('BlogSearchForm');
     return $form;
 }
Example #10
0
 public static function page_upload_content()
 {
     $theme = new Theme();
     if (isset($_FILES['file'])) {
         $file = new FileObject();
         if ($file->uploadFile($_FILES['file'])) {
             Notification::statusNotify(t("Le fichier a bien été uploadé."), Notification::STATUS_SUCCESS);
         } else {
             Notification::statusNotify(t("Une erreur s'est produite lors de l'upload."), Notification::STATUS_ERROR);
         }
     }
     $f = new Form("POST", Page::url("/file/upload"));
     $f->setAttribute("enctype", "multipart/form-data");
     $t = new InputElement("file", t("Fichier : "), "", "file");
     $f->addElement($t);
     $t = new InputElement("submit-file", "", t("Charger"), "submit");
     $f->addElement($t);
     $formulaire = $theme->forming($f);
     $theme->set_title("Charger un fichier");
     $theme->add_to_body($formulaire);
     $theme->process_theme(Theme::STRUCT_ADMIN);
     return;
 }
 /**
  * Return a form with a dropdown to select the list you want to use
  * 
  * @return Form
  */
 public function ListForm()
 {
     $crumbs = $this->Breadcrumbs();
     if ($crumbs && $crumbs->count() >= 2) {
         $one_level_up = $crumbs->offsetGet($crumbs->count() - 2);
     }
     $record_ids = "";
     $query_string = "";
     foreach ($this->getRecordIDList() as $id) {
         $record_ids .= $id . ',';
         $query_string .= "records[]={$id}&";
     }
     // Cut off the last 2 parts of the string
     $record_ids = substr($record_ids, 0, -1);
     $query_string = substr($query_string, 0, -1);
     $form = new Form($this, 'ListForm', $fields = new FieldList(HiddenField::create("RecordIDs", "", $record_ids), DropdownField::create("ContactListID", _t("Contacts.ChooseList", "Choose a list"), ContactList::get()->map())->setEmptyString(_t("Contacts.SelectList", "Select a List"))), $actions = new FieldList(FormAction::create('doAddToList', _t("Contacts.Add", 'Add'))->setAttribute('id', 'bulkEditingAddToListBtn')->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept')->setUseButtonTag(true), FormAction::create('Cancel', _t('GRIDFIELD_BULKMANAGER_EDIT_HANDLER.CANCEL_BTN_LABEL', 'Cancel'))->setAttribute('id', 'bulkEditingUpdateCancelBtn')->addExtraClass('ss-ui-action-destructive cms-panel-link')->setAttribute('data-icon', 'decline')->setAttribute('href', $one_level_up->Link)->setUseButtonTag(true)));
     if ($crumbs && $crumbs->count() >= 2) {
         $form->Backlink = $one_level_up->Link;
     }
     // override form action URL back to bulkEditForm
     // and add record ids GET var
     $form->setAttribute('action', $this->Link('ListForm?' . $query_string));
     return $form;
 }
 public function CountriesForm()
 {
     $shopConfig = ShopConfig::get()->First();
     $fields = new FieldList($rootTab = new TabSet("Root", $tabMain = new Tab('Shipping', new HiddenField('ShopConfigSection', null, 'Countries'), new GridField('ShippingCountries', 'Shipping Countries', $shopConfig->ShippingCountries(), GridFieldConfig_RecordEditor::create()->removeComponentsByType('GridFieldFilterHeader')->removeComponentsByType('GridFieldAddExistingAutocompleter'))), new Tab('Billing', new GridField('BillingCountries', 'Billing Countries', $shopConfig->BillingCountries(), GridFieldConfig_RecordEditor::create()->removeComponentsByType('GridFieldFilterHeader')->removeComponentsByType('GridFieldAddExistingAutocompleter')))));
     $actions = new FieldList();
     $form = new Form($this, 'EditForm', $fields, $actions);
     $form->setTemplate('ShopAdminSettings_EditForm');
     $form->setAttribute('data-pjax-fragment', 'CurrentForm');
     $form->addExtraClass('cms-content cms-edit-form center ss-tabset');
     if ($form->Fields()->hasTabset()) {
         $form->Fields()->findOrMakeTab('Root')->setTemplate('CMSTabSet');
     }
     $form->setFormAction(Controller::join_links($this->Link($this->sanitiseClassName($this->modelClass)), 'Countries/CountriesForm'));
     $form->loadDataFrom($shopConfig);
     return $form;
 }
Example #13
0
function filter_form_vpn()
{
    global $filter_active, $rawfilter, $filterfieldsarray, $filtertext, $filterlogentries_qty, $nentries, $Include_Act, $interfacefilter;
    global $logfile;
    global $system_logs_filter_form_hidden;
    if ($filter_active) {
        $panel_state = 'in';
        $panel_body_state = SEC_OPEN;
    } else {
        if ($system_logs_filter_form_hidden) {
            $panel_state = 'out';
            $panel_body_state = SEC_OPEN;
        } else {
            $panel_state = 'in';
            $panel_body_state = SEC_CLOSED;
        }
    }
    if (!$rawfilter) {
        // Advanced log filter form
        $form = new Form(false);
        $form->setAttribute('id', 'filter-form')->addClass('collapse ' . $panel_state);
        $section = new Form_Section('Advanced Log Filter', 'filter-panel', COLLAPSIBLE | $panel_body_state);
        if ($logfile == "vpn") {
            $group = new Form_Group('');
            $group->add(new Form_Input('filterlogentries_time', null, 'text', $filterfieldsarray['time']))->setWidth(3)->setHelp('Time');
            $group->add(new Form_Input('filterlogentries_action', null, 'text', $filterfieldsarray['action']))->setWidth(3)->setHelp('Action');
            $group->add(new Form_Input('filterlogentries_qty', null, 'number', $filterlogentries_qty, ['placeholder' => $nentries]))->setWidth(2)->setHelp('Quantity');
            $section->add($group);
            $group = new Form_Group('');
            $group->add(new Form_Input('filterlogentries_user', null, 'text', $filterfieldsarray['user']))->setWidth(3)->setHelp('User');
            $group->add(new Form_Input('filterlogentries_ip_address', null, 'text', $filterfieldsarray['ip_address']))->setWidth(4)->setHelp('IP Address');
        } else {
            $group = new Form_Group('');
            $group->add(new Form_Input('filterlogentries_time', null, 'text', $filterfieldsarray['time']))->setWidth(3)->setHelp('Time');
            $group->add(new Form_Input('filterlogentries_type', null, 'text', $filterfieldsarray['type']))->setWidth(2)->setHelp('Type');
            $group->add(new Form_Input('filterlogentries_pid', null, 'text', $filterfieldsarray['pid']))->setWidth(2)->setHelp('PID');
            $group->add(new Form_Input('filterlogentries_qty', null, 'number', $filterlogentries_qty, ['placeholder' => $nentries]))->setWidth(2)->setHelp('Quantity');
            $section->add($group);
            $group = new Form_Group('');
            $group->add(new Form_Input('filterlogentries_message', null, 'text', $filterfieldsarray['message']))->setWidth(7)->setHelp('Log Message');
        }
        $btnsubmit = new Form_Button('filterlogentries_submit', ' ' . gettext('Apply Filter'), null, 'fa-filter');
    } else {
        // Simple log filter form
        $form = new Form(false);
        $form->setAttribute('id', 'filter-form')->addClass('collapse ' . $panel_state);
        $section = new Form_Section('Log Filter', 'filter-panel', COLLAPSIBLE | $panel_body_state);
        $group = new Form_Group('');
        $group->add(new Form_Input('filtertext', null, 'text', $filtertext))->setWidth(6)->setHelp('Filter Expression');
        $group->add(new Form_Input('filterlogentries_qty', null, 'number', $filterlogentries_qty, ['placeholder' => $nentries]))->setWidth(2)->setHelp('Quantity');
        $btnsubmit = new Form_Button('filtersubmit', ' ' . gettext('Apply Filter'), null, 'fa-filter');
    }
    $btnsubmit->removeClass('btn-primary')->addClass('btn-success')->addClass('btn-sm');
    $group->add(new Form_StaticText('', $btnsubmit));
    $group->setHelp('<a target="_blank" href="http://www.php.net/manual/en/book.pcre.php">' . gettext('Regular expression reference') . '</a> ' . gettext('Precede with exclamation (!) to exclude match.'));
    $section->add($group);
    $form->add($section);
    print $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;
 }
Example #15
0
// +---------------------------------------------------------------------------+
// | This file is part of the Openology FrameWork                              |
// | Copyright (c) 2004-2005 Openology.org Team                                |
// |                                                                           |
// | For the full copyright and license information, please view the COPYRIGHT |
// | file that was distributed with this source code. If the COPYRIGHT file is |
// | missing, please visit Openology homepage: http://www.openology.org/       |
// +---------------------------------------------------------------------------+
//
// $Id:
include_once OOO_APP_MODULES . '/page.php';
include_once OOO_CORE . '/form/Form.php';
include_once OOO_CORE . '/form/FormController.php';
$form = new Form('login_form', 'index.php', 'post');
$form->setAttribute('id', 'login_form');
$text1 =& $form->addElement('text');
$text1->setAttribute('id', 'username');
$text1->setAttribute('tabindex', '1');
$text1->setAttribute('title', 'Enter your User name');
$text1->addRule('required', 'client', 'Please input username!');
$text5 =& $form->addElement('password');
$text5->setAttribute('id', 'password');
$text5->setAttribute('tabindex', '2');
$text5->setAttribute('title', 'Enter your Password');
$text5->addRule('required', 'client', 'Please input password!');
$text5->addRule('MD5', 'client', '');
$button1 =& $form->addElement('reset');
$button1->setAttribute('id', 'resetbutton');
$button1->setAttribute('value', 'Cancel');
$button1->setAttribute('title', 'Click to clear info');
Example #16
0
 public static function page_set_avatar()
 {
     $theme = new Theme();
     if (isset($_FILES['file'])) {
         $file = new FileObject();
         if ($id_file = $file->uploadFile($_FILES['file'])) {
             $u = User::get_user_logged();
             $u->set_avatar($id_file);
             header("location: " . Page::url("/profile"));
             return;
         } else {
             Notification::statusNotify(t("Une erreur s'est produite lors de l'upload."), Notification::STATUS_ERROR);
         }
     }
     $f = new Form("POST", Page::url("/profile/settings/avatar"));
     $f->setAttribute("enctype", "multipart/form-data");
     $t = new InputElement("file", t("Fichier : "), "", "file");
     $f->addElement($t);
     $t = new InputElement("submit-file", "", t("Charger"), "submit");
     $f->addElement($t);
     $formulaire = $theme->forming($f);
     $theme->set_title("Changer mon avatar");
     $theme->add_to_body($formulaire);
     $theme->process_theme(Theme::STRUCT_ADMIN);
     return;
 }
Example #17
0
 public function getEditForm($id = null, $fields = null)
 {
     $list = $this->getList();
     $exportButton = new GridFieldExportButton('before');
     $exportButton->setExportColumns($this->getExportFields());
     $listField = GridField::create($this->sanitiseClassName($this->modelClass), false, $list, $fieldConfig = GridFieldConfig_RecordEditor::create($this->stat('page_length'))->addComponent($exportButton)->removeComponentsByType('GridFieldFilterHeader')->addComponents(new GridFieldPrintButton('before')));
     // Validation
     if (singleton($this->modelClass)->hasMethod('getCMSValidator')) {
         $detailValidator = singleton($this->modelClass)->getCMSValidator();
         $listField->getConfig()->getComponentByType('GridFieldDetailForm')->setValidator($detailValidator);
     }
     $form = new Form($this, 'EditForm', new FieldList($listField), new FieldList());
     $form->addExtraClass('cms-edit-form cms-panel-padded center');
     $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
     $editFormAction = Controller::join_links($this->Link($this->sanitiseClassName($this->modelClass)), 'EditForm');
     $form->setFormAction($editFormAction);
     $form->setAttribute('data-pjax-fragment', 'CurrentForm');
     $this->extend('updateEditForm', $form);
     return $form;
 }
 /**
  * Builds an item edit form.  The arguments to getCMSFields() are the popupController and
  * popupFormName, however this is an experimental API and may change.
  *
  * @todo In the future, we will probably need to come up with a tigher object representing a partially
  * complete controller with gaps for extra functionality.  This, for example, would be a better way
  * of letting Security/login put its log-in form inside a UI specified elsewhere.
  *
  * @return Form
  */
 public function ItemEditForm()
 {
     $list = $this->gridField->getList();
     if (empty($this->record)) {
         $controller = $this->getToplevelController();
         $url = $controller->getRequest()->getURL();
         $noActionURL = $controller->removeAction($url);
         $controller->getResponse()->removeHeader('Location');
         //clear the existing redirect
         return $controller->redirect($noActionURL, 302);
     }
     $canView = $this->record->canView();
     $canEdit = $this->record->canEdit();
     $canDelete = $this->record->canDelete();
     $canCreate = $this->record->canCreate();
     if (!$canView) {
         $controller = $this->getToplevelController();
         // TODO More friendly error
         return $controller->httpError(403);
     }
     // Build actions
     $actions = $this->getFormActions();
     // If we are creating a new record in a has-many list, then
     // pre-populate the record's foreign key.
     if ($list instanceof HasManyList && !$this->record->isInDB()) {
         $key = $list->getForeignKey();
         $id = $list->getForeignID();
         $this->record->{$key} = $id;
     }
     $fields = $this->component->getFields();
     if (!$fields) {
         $fields = $this->record->getCMSFields();
     }
     // If we are creating a new record in a has-many list, then
     // Disable the form field as it has no effect.
     if ($list instanceof HasManyList) {
         $key = $list->getForeignKey();
         if ($field = $fields->dataFieldByName($key)) {
             $fields->makeFieldReadonly($field);
         }
     }
     // Caution: API violation. Form expects a Controller, but we are giving it a RequestHandler instead.
     // Thanks to this however, we are able to nest GridFields, and also access the initial Controller by
     // dereferencing GridFieldDetailForm_ItemRequest->getController() multiple times. See getToplevelController
     // below.
     $form = new Form($this, 'ItemEditForm', $fields, $actions, $this->component->getValidator());
     $form->loadDataFrom($this->record, $this->record->ID == 0 ? Form::MERGE_IGNORE_FALSEISH : Form::MERGE_DEFAULT);
     if ($this->record->ID && !$canEdit) {
         // Restrict editing of existing records
         $form->makeReadonly();
         // Hack to re-enable delete button if user can delete
         if ($canDelete) {
             $form->Actions()->fieldByName('action_doDelete')->setReadonly(false);
         }
     } elseif (!$this->record->ID && !$canCreate) {
         // Restrict creation of new records
         $form->makeReadonly();
     }
     // Load many_many extraData for record.
     // Fields with the correct 'ManyMany' namespace need to be added manually through getCMSFields().
     if ($list instanceof ManyManyList) {
         $extraData = $list->getExtraData('', $this->record->ID);
         $form->loadDataFrom(array('ManyMany' => $extraData));
     }
     // TODO Coupling with CMS
     $toplevelController = $this->getToplevelController();
     if ($toplevelController && $toplevelController instanceof LeftAndMain) {
         // Always show with base template (full width, no other panels),
         // regardless of overloaded CMS controller templates.
         // TODO Allow customization, e.g. to display an edit form alongside a search form from the CMS controller
         $form->setTemplate('LeftAndMain_EditForm');
         $form->addExtraClass('cms-content cms-edit-form center');
         $form->setAttribute('data-pjax-fragment', 'CurrentForm Content');
         if ($form->Fields()->hasTabset()) {
             $form->Fields()->findOrMakeTab('Root')->setTemplate('CMSTabSet');
             $form->addExtraClass('cms-tabset');
         }
         $form->Backlink = $this->getBackLink();
     }
     $cb = $this->component->getItemEditFormCallback();
     if ($cb) {
         $cb($form, $this);
     }
     $this->extend("updateItemEditForm", $form);
     return $form;
 }
Example #19
0
 /**
  * Builds an item edit form.  The arguments to getCMSFields() are the popupController and
  * popupFormName, however this is an experimental API and may change.
  * 
  * @todo In the future, we will probably need to come up with a tigher object representing a partially
  * complete controller with gaps for extra functionality.  This, for example, would be a better way
  * of letting Security/login put its log-in form inside a UI specified elsewhere.
  * 
  * @return Form 
  */
 public function ItemEditForm()
 {
     $list = $this->gridField->getList();
     if (empty($this->record)) {
         $controller = $this->getToplevelController();
         $noActionURL = $controller->removeAction($_REQUEST['url']);
         $controller->getResponse()->removeHeader('Location');
         //clear the existing redirect
         return $controller->redirect($noActionURL, 302);
     }
     $canView = $this->record->canView();
     $canEdit = $this->record->canEdit();
     $canDelete = $this->record->canDelete();
     $canCreate = $this->record->canCreate();
     if (!$canView) {
         $controller = $this->getToplevelController();
         // TODO More friendly error
         return $controller->httpError(403);
     }
     $actions = new FieldList();
     if ($this->record->ID !== 0) {
         if ($canEdit) {
             $actions->push(FormAction::create('doSave', _t('GridFieldDetailForm.Save', 'Save'))->setUseButtonTag(true)->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept'));
         }
         if ($canDelete) {
             $actions->push(FormAction::create('doDelete', _t('GridFieldDetailForm.Delete', 'Delete'))->setUseButtonTag(true)->addExtraClass('ss-ui-action-destructive action-delete'));
         }
     } else {
         // adding new record
         //Change the Save label to 'Create'
         $actions->push(FormAction::create('doSave', _t('GridFieldDetailForm.Create', 'Create'))->setUseButtonTag(true)->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'add'));
         // Add a Cancel link which is a button-like link and link back to one level up.
         $curmbs = $this->Breadcrumbs();
         if ($curmbs && $curmbs->count() >= 2) {
             $one_level_up = $curmbs->offsetGet($curmbs->count() - 2);
             $text = sprintf("<a class=\"%s\" href=\"%s\">%s</a>", "crumb ss-ui-button ss-ui-action-destructive cms-panel-link ui-corner-all", $one_level_up->Link, _t('GridFieldDetailForm.CancelBtn', 'Cancel'));
             $actions->push(new LiteralField('cancelbutton', $text));
         }
     }
     $fields = $this->component->getFields();
     if (!$fields) {
         $fields = $this->record->getCMSFields();
     }
     // If we are creating a new record in a has-many list, then
     // pre-populate the record's foreign key. Also disable the form field as
     // it has no effect.
     if ($list instanceof HasManyList) {
         $key = $list->getForeignKey();
         $id = $list->getForeignID();
         if (!$this->record->isInDB()) {
             $this->record->{$key} = $id;
         }
         if ($field = $fields->dataFieldByName($key)) {
             $fields->makeFieldReadonly($field);
         }
     }
     // Caution: API violation. Form expects a Controller, but we are giving it a RequestHandler instead.
     // Thanks to this however, we are able to nest GridFields, and also access the initial Controller by
     // dereferencing GridFieldDetailForm_ItemRequest->getController() multiple times. See getToplevelController
     // below.
     $form = new Form($this, 'ItemEditForm', $fields, $actions, $this->component->getValidator());
     $form->loadDataFrom($this->record, $this->record->ID == 0 ? Form::MERGE_IGNORE_FALSEISH : Form::MERGE_DEFAULT);
     if ($this->record->ID && !$canEdit) {
         // Restrict editing of existing records
         $form->makeReadonly();
         // Hack to re-enable delete button if user can delete
         if ($canDelete) {
             $form->Actions()->fieldByName('action_doDelete')->setReadonly(false);
         }
     } elseif (!$this->record->ID && !$canCreate) {
         // Restrict creation of new records
         $form->makeReadonly();
     }
     // Load many_many extraData for record.
     // Fields with the correct 'ManyMany' namespace need to be added manually through getCMSFields().
     if ($list instanceof ManyManyList) {
         $extraData = $list->getExtraData('', $this->record->ID);
         $form->loadDataFrom(array('ManyMany' => $extraData));
     }
     // TODO Coupling with CMS
     $toplevelController = $this->getToplevelController();
     if ($toplevelController && $toplevelController instanceof LeftAndMain) {
         // Always show with base template (full width, no other panels),
         // regardless of overloaded CMS controller templates.
         // TODO Allow customization, e.g. to display an edit form alongside a search form from the CMS controller
         $form->setTemplate('LeftAndMain_EditForm');
         $form->addExtraClass('cms-content cms-edit-form center');
         $form->setAttribute('data-pjax-fragment', 'CurrentForm Content');
         if ($form->Fields()->hasTabset()) {
             $form->Fields()->findOrMakeTab('Root')->setTemplate('CMSTabSet');
             $form->addExtraClass('cms-tabset');
         }
         $form->Backlink = $this->getBackLink();
     }
     $cb = $this->component->getItemEditFormCallback();
     if ($cb) {
         $cb($form, $this);
     }
     $this->extend("updateItemEditForm", $form);
     return $form;
 }
 public function upload()
 {
     $form = new Form('form-upload', Router::getInstance()->build('UploadController', 'upload'));
     $form->setAttribute('data-noajax', 'true');
     $form->setEnctype();
     $fieldset = new Fieldset(System::getLanguage()->_('General'));
     $folderInput = new Select('folder', System::getLanguage()->_('ChooseFolder'), Folder::getAll());
     $folderInput->selected_value = Utils::getGET('parent', NULL);
     $fieldset->addElements($folderInput);
     $form->addElements($fieldset);
     $fieldset = new Fieldset(System::getLanguage()->_('FileUpload'));
     $fileInput = new FileUpload('file', System::getLanguage()->_('ChooseFile'), false);
     $fieldset->addElements($fileInput);
     $form->addElements($fieldset);
     if (DOWNLOAD_VIA_SERVER) {
         $fieldset = new Fieldset(System::getLanguage()->_('UploadFromURL'));
         $url = new Text('url', System::getLanguage()->_('EnterURL'), false);
         $name = new Text('name', System::getLanguage()->_('Name'), false);
         $name->setValue(System::getLanguage()->_('DownloadedFile'));
         $fieldset->addElements($url, $name);
         $form->addElements($fieldset);
     }
     $fieldset = new Fieldset(System::getLanguage()->_('PermissionSetting'));
     $permissionInput = new Select('permissions', System::getLanguage()->_('Permission'), FilePermissions::getAll());
     $permissionInput->selected_value = DEFAULT_FILE_PERMISSION;
     $password = new Password('password', System::getLanguage()->_('Password'), false);
     $fieldset->addElements($permissionInput, $password);
     $form->addElements($fieldset);
     if (Utils::getPOST('submit', false) != false) {
         if ($permissionInput->selected_value == 2 && empty($password->value)) {
             $password->error = System::getLanguage()->_('ErrorEmptyTextfield');
         } else {
             if ($form->validate() && (!empty($url->value) || !empty($fileInput->uploaded_file))) {
                 // Specify input control for error display
                 $err = empty($url->value) ? $fileInput : $url;
                 try {
                     $folder = Folder::find('_id', $folderInput->selected_value);
                     $file = new File();
                     $file->folder = $folder;
                     $file->permission = $permissionInput->selected_value;
                     $file->password = $password->value;
                     if (empty($url->value)) {
                         $file->filename = $fileInput->filename;
                         $file->upload($fileInput->uploaded_file);
                     } else {
                         $file->filename = $name->value;
                         $file->remote($url->value);
                     }
                     $file->save();
                     System::forwardToRoute(Router::getInstance()->build('BrowserController', 'show', $folder));
                     exit;
                 } catch (UploadException $e) {
                     $fileInput->filename = '';
                     $fileInput->uploaded_file = '';
                     $err->error = $e->getMessage();
                     if ($e->getCode() != 0) {
                         $err->error .= ' Code: ' . $e->getCode();
                     }
                 } catch (QuotaExceededException $e) {
                     $err->error = System::getLanguage()->_('ErrorQuotaExceeded');
                 } catch (Exception $e) {
                     $fileInput->filename = '';
                     $fileInput->uploaded_file = '';
                     $err->error = System::getLanguage()->_('ErrorWhileUpload') . ' ' . $e->getMessage();
                 }
             }
         }
     }
     $form->setSubmit(new Button(System::getLanguage()->_('Upload'), 'open'));
     if ($folderInput->selected_value == 0) {
         $form->addButton(new Button(System::getLanguage()->_('Cancel'), '', Router::getInstance()->build('BrowserController', 'index')));
     } else {
         $form->addButton(new Button(System::getLanguage()->_('Cancel'), '', Router::getInstance()->build('BrowserController', 'show', new Folder($folderInput->selected_value))));
     }
     $smarty = new Template();
     $smarty->assign('title', System::getLanguage()->_('Upload'));
     $smarty->assign('heading', System::getLanguage()->_('FileUpload'));
     $smarty->assign('form', $form->__toString());
     $smarty->assign('BODY_CLASS', 'preventreload');
     $smarty->requireResource('upload');
     $smarty->display('form.tpl');
 }
Example #21
0
 public function AttributeSettingsForm()
 {
     $shopConfig = ShopConfig::get()->First();
     $fields = new FieldList($rootTab = new TabSet('Root', $tabMain = new Tab('Attribute', GridField::create('Attributes', 'Attributes', $shopConfig->Attributes(), GridFieldConfig_HasManyRelationEditor::create()))));
     $actions = new FieldList();
     $actions->push(FormAction::create('saveAttributeSettings', _t('GridFieldDetailForm.Save', 'Save'))->setUseButtonTag(true)->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'add'));
     $form = new Form($this, 'EditForm', $fields, $actions);
     $form->setTemplate('ShopAdminSettings_EditForm');
     $form->setAttribute('data-pjax-fragment', 'CurrentForm');
     $form->addExtraClass('cms-content cms-edit-form center ss-tabset');
     if ($form->Fields()->hasTabset()) {
         $form->Fields()->findOrMakeTab('Root')->setTemplate('CMSTabSet');
     }
     $form->setFormAction(Controller::join_links($this->Link($this->sanitiseClassName($this->modelClass)), 'Attribute/AttributeSettingsForm'));
     $form->loadDataFrom($shopConfig);
     return $form;
 }
Example #22
0
 /**
  * Returns a placeholder form, used by {@link getEditForm()} if no record is selected.
  * Our javascript logic always requires a form to be present in the CMS interface.
  * 
  * @return Form
  */
 function EmptyForm()
 {
     $form = new Form($this, "EditForm", new FieldList(), new FieldList());
     $form->unsetValidator();
     $form->addExtraClass('cms-edit-form');
     $form->addExtraClass('root-form');
     $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
     $form->setAttribute('data-pjax-fragment', 'CurrentForm');
     return $form;
 }
 /**
  * Gets the form used for viewing snippets
  * @param {int} $id ID of the record to fetch
  * @param {FieldList} $fields Fields to use
  * @return {Form} Form to be used
  */
 public function getEditForm($id = null, $fields = null)
 {
     if (!$id) {
         $id = $this->currentPageID();
     }
     $form = parent::getEditForm($id);
     $record = $this->getRecord($id);
     if ($record && !$record->canView()) {
         return Security::permissionFailure($this);
     }
     if (!$fields) {
         $fields = $form->Fields();
     }
     $actions = $form->Actions();
     if ($record) {
         $fields->push($idField = new HiddenField("ID", false, $id));
         $versions = $record->Versions()->filter('ID:not', $record->CurrentVersionID)->Map('ID', 'Created');
         $actions = new FieldList(new FormAction('doCopy', _t('CodeBank.COPY', '_Copy')), new FormAction('doEditRedirect', _t('CodeBank.EDIT', '_Edit')), new FormAction('doExport', _t('CodeBank.EXPORT', '_Export')), new FormAction('doPrint', _t('CodeBank.PRINT', '_Print')), new LabelField('Revision', _t('CodeBank.REVISION', '_Revision') . ': '), DropdownField::create('RevisionID', '', $versions, $this->urlParams['OtherID'])->setEmptyString('{' . _t('CodeBank.CURRENT_REVISION', '_Current Revision') . '}')->setDisabled($record->Versions()->Count() <= 1)->addExtraClass('no-change-track'), FormAction::create('compareRevision', _t('CodeBank.COMPARE_WITH_CURRENT', '_Compare with Current'))->setDisabled($record->Versions()->Count() <= 1 || empty($this->urlParams['OtherID']) || !is_numeric($this->urlParams['OtherID'])));
         // Use <button> to allow full jQuery UI styling
         $actionsFlattened = $actions->dataFields();
         if ($actionsFlattened) {
             foreach ($actionsFlattened as $action) {
                 if ($action instanceof FormAction) {
                     $action->setUseButtonTag(true);
                 }
             }
         }
         if ($record->hasMethod('getCMSValidator')) {
             $validator = $record->getCMSValidator();
         } else {
             $validator = new RequiredFields();
         }
         if ($record->Package() && $record->Package() !== false && $record->Package()->ID != 0) {
             $package = new ArrayList(array($record->Package()));
         } else {
             $package = null;
         }
         $fields->insertBefore($fields->dataFieldByName('Title'), 'LanguageID');
         $fields->replaceField('PackageID', new PackageViewField('PackageID', _t('Snippet.PACKAGE', '_Package'), $package, $record->ID));
         $fields->replaceField('Text', HighlightedContentField::create('SnippetText', _t('Snippet.CODE', '_Code'), $record->Language()->HighlightCode)->setForm($form));
         $fields->replaceField('Tags', new TagsViewField('Tags', _t('Snippet.TAGS_COLUMN', '_Tags')));
         $fields->addFieldToTab('Root.Main', $creator = ReadonlyField::create('CreatorName', _t('CodeBank.CREATOR', '_Creator'), $record->Creator() && $record->Creator()->ID > 0 ? '<a href="' . $this->Link() . '?creator=' . $record->CreatorID . '">' . $record->Creator()->Name . '</a>' : _t('CodeBank.UNKNOWN_USER', '_Unknown User'))->setForm($form));
         $creator->dontEscape = true;
         $fields->addFieldToTab('Root.Main', ReadonlyField::create('LanguageName', _t('CodeBank.LANGUAGE', '_Language'), $record->Language()->Name)->setForm($form));
         $fields->addFieldToTab('Root.Main', DatetimeField_Readonly::create('LastModified', _t('CodeBank.LAST_MODIFIED', '_Last Modified'), $record->CurrentVersion->LastEdited)->setForm($form));
         $fields->addFieldToTab('Root.Main', ReadonlyField::create('LastEditorName', _t('CodeBank.LAST_EDITED_BY', '_Last Edited By'), $record->LastEditor() && $record->LastEditor()->ID > 0 ? $record->LastEditor()->Name : _t('CodeBank.UNKNOWN_USER', '_Unknown User'))->setForm($form));
         $fields->addFieldToTab('Root.Main', ReadonlyField::create('SnippetID', _t('CodeBank.ID', '_ID'), $record->ID));
         $fields->addFieldToTab('Root.Main', ReadonlyField::create('CurrentVersionID', _t('CodeBank.VERSION', '_Version')));
         $fields->push(new HiddenField('ID', 'ID'));
         $form = new Form($this, 'EditForm', $fields, $actions, $validator);
         $form->loadDataFrom($record);
         $form->disableDefaultAction();
         $form->addExtraClass('cms-edit-form');
         $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
         $form->addExtraClass('center ' . $this->BaseCSSClasses());
         $form->setAttribute('data-pjax-fragment', 'CurrentForm');
         //Swap content for version text
         if (!empty($this->urlParams['OtherID']) && is_numeric($this->urlParams['OtherID'])) {
             $version = $record->Version(intval($this->urlParams['OtherID']));
             if (!empty($version) && $version !== false && $version->ID != 0) {
                 $fields->dataFieldByName('SnippetText')->setValue($version->Text);
                 $fields->dataFieldByName('LastModified')->setValue($version->LastEdited);
                 $fields->dataFieldByName('CurrentVersionID')->setValue($version->ID);
             }
             $form->Fields()->insertBefore(new LiteralField('NotCurrentVersion', '<p class="message warning">' . _t('CodeBank.NOT_CURRENT_VERSION', '_You are viewing a past version of this snippet\'s content, {linkopen}click here{linkclose} to view the current version', array('linkopen' => '<a href="admin/codeBank/show/' . $record->ID . '">', 'linkclose' => '</a>')) . '</p>'), 'Title');
         }
         $readonlyFields = $form->Fields()->makeReadonly();
         $form->setFields($readonlyFields);
         $this->extend('updateEditForm', $form);
         $form->Actions()->push(new LiteralField('CodeBankVersion', '<p class="codeBankVersion">Code Bank: ' . $this->getVersion() . '</p>'));
         Requirements::add_i18n_javascript(CB_DIR . '/javascript/lang');
         Requirements::add_i18n_javascript('mysite/javascript/lang');
         Requirements::javascript(CB_DIR . '/javascript/external/jquery-zclip/jquery.zclip.min.js');
         Requirements::javascript(CB_DIR . '/javascript/CodeBank.ViewForm.js');
         //Display message telling user to run dev/build because the version numbers are out of sync
         if (CB_VERSION != '@@VERSION@@' && CodeBankConfig::CurrentConfig()->Version != CB_VERSION . ' ' . CB_BUILD_DATE) {
             $form->Fields()->insertBefore(new LiteralField('DBUpgrade', '<p class="message error">' . _t('CodeBank.UPDATE_NEEDED', '_A database upgrade is required please run {startlink}dev/build{endlink}.', array('startlink' => '<a href="dev/build?flush=all">', 'endlink' => '</a>')) . '</p>'), 'Title');
         } else {
             if ($this->hasOldTables()) {
                 $form->Fields()->insertBefore(new LiteralField('DBUpgrade', '<p class="message warning">' . _t('CodeBank.MIGRATION_AVAILABLE', '_It appears you are upgrading from Code Bank 2.2.x, your old data can be migrated {startlink}click here to begin{endlink}, though it is recommended you backup your database first.', array('startlink' => '<a href="dev/tasks/CodeBankLegacyMigrate">', 'endlink' => '</a>')) . '</p>'), 'Title');
             }
         }
         return $form;
     } else {
         if ($id) {
             $form = CMSForm::create($this, 'EditForm', new FieldList(new TabSet('Root', new Tab('Main', ' ', new LabelField('DoesntExistLabel', _t('CodeBank.SNIPPIT_NOT_EXIST', '_Snippit does not exist'))))), new FieldList())->setHTMLID('Form_EditForm');
             $form->addExtraClass('cms-edit-form');
             $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
             $form->addExtraClass('center ' . $this->BaseCSSClasses());
             $form->setAttribute('data-pjax-fragment', 'CurrentForm');
             //Display message telling user to run dev/build because the version numbers are out of sync
             if (CB_VERSION != '@@VERSION@@' && CodeBankConfig::CurrentConfig()->Version != CB_VERSION . ' ' . CB_BUILD_DATE) {
                 $form->Fields()->insertBefore(new LiteralField('DBUpgrade', '<p class="message error">' . _t('CodeBank.UPDATE_NEEDED', '_A database upgrade is required please run {startlink}dev/build{endlink}.', array('startlink' => '<a href="dev/build?flush=all">', 'endlink' => '</a>')) . '</p>'), 'DoesntExist');
             } else {
                 if ($this->hasOldTables()) {
                     $form->Fields()->insertBefore(new LiteralField('DBUpgrade', '<p class="message warning">' . _t('CodeBank.MIGRATION_AVAILABLE', '_It appears you are upgrading from Code Bank 2.2.x, your old data can be migrated {startlink}click here to begin{endlink}, though it is recommended you backup your database first.', array('startlink' => '<a href="dev/tasks/CodeBankLegacyMigrate">', 'endlink' => '</a>')) . '</p>'), 'DoesntExistLabel');
                 }
             }
         } else {
             $form = $this->EmptyForm();
             if (Session::get('CodeBank.deletedSnippetID')) {
                 $form->Fields()->push(new HiddenField('ID', 'ID', Session::get('CodeBank.deletedSnippetID')));
             }
             //Display message telling user to run dev/build because the version numbers are out of sync
             if (CB_VERSION != '@@VERSION@@' && CodeBankConfig::CurrentConfig()->Version != CB_VERSION . ' ' . CB_BUILD_DATE) {
                 $form->Fields()->push(new LiteralField('DBUpgrade', '<p class="message error">' . _t('CodeBank.UPDATE_NEEDED', '_A database upgrade is required please run {startlink}dev/build{endlink}.', array('startlink' => '<a href="dev/build?flush=all">', 'endlink' => '</a>')) . '</p>'));
             } else {
                 if ($this->hasOldTables()) {
                     $form->Fields()->push(new LiteralField('DBUpgrade', '<p class="message warning">' . _t('CodeBank.MIGRATION_AVAILABLE', '_It appears you are upgrading from Code Bank 2.2.x, your old data can be migrated {startlink}click here to begin{endlink}, though it is recommended you backup your database first.', array('startlink' => '<a href="dev/tasks/CodeBankLegacyMigrate">', 'endlink' => '</a>')) . '</p>'));
                 }
             }
         }
     }
     $form->disableDefaultAction();
     $form->addExtraClass('cms-edit-form');
     $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
     $form->addExtraClass('center ' . $this->BaseCSSClasses());
     $form->Actions()->push(new LiteralField('CodeBankVersion', '<p class="codeBankVersion">Code Bank: ' . $this->getVersion() . '</p>'));
     return $form;
 }
 /**
  * Return the form for editing
  */
 function getEditForm($id = null, $fields = null)
 {
     $record = null;
     if (!$id) {
         $id = $this->getCurrentPageID();
     }
     if ($id && $id != "root") {
         $record = $this->getRecord($id);
     }
     if ($record) {
         $fields = $record->getCMSFields();
         // If we're editing an external source or item, and it can be imported
         // then add the "Import" tab.
         $isSource = $record instanceof ExternalContentSource;
         $isItem = $record instanceof ExternalContentItem;
         if (($isSource || $isItem) && $record->canImport()) {
             $allowedTypes = $record->allowedImportTargets();
             if (isset($allowedTypes['sitetree'])) {
                 $fields->addFieldToTab('Root.Import', new TreeDropdownField("MigrationTarget", _t('ExternalContent.MIGRATE_TARGET', 'Page to import into'), 'SiteTree'));
             }
             if (isset($allowedTypes['file'])) {
                 $fields->addFieldToTab('Root.Import', new TreeDropdownField("FileMigrationTarget", _t('ExternalContent.FILE_MIGRATE_TARGET', 'Folder to import into'), 'Folder'));
             }
             $fields->addFieldToTab('Root.Import', new CheckboxField("IncludeSelected", _t('ExternalContent.INCLUDE_SELECTED', 'Include Selected Item in Import')));
             $fields->addFieldToTab('Root.Import', new CheckboxField("IncludeChildren", _t('ExternalContent.INCLUDE_CHILDREN', 'Include Child Items in Import'), true));
             $duplicateOptions = array(ExternalContentTransformer::DS_OVERWRITE => ExternalContentTransformer::DS_OVERWRITE, ExternalContentTransformer::DS_DUPLICATE => ExternalContentTransformer::DS_DUPLICATE, ExternalContentTransformer::DS_SKIP => ExternalContentTransformer::DS_SKIP);
             $fields->addFieldToTab('Root.Import', new OptionsetField("DuplicateMethod", _t('ExternalContent.DUPLICATES', 'Select how duplicate items should be handled'), $duplicateOptions, $duplicateOptions[ExternalContentTransformer::DS_SKIP]));
             if (class_exists('QueuedJobDescriptor')) {
                 $repeats = array(0 => 'None', 300 => '5 minutes', 900 => '15 minutes', 1800 => '30 minutes', 3600 => '1 hour', 33200 => '12 hours', 86400 => '1 day', 604800 => '1 week');
                 $fields->addFieldToTab('Root.Import', new DropdownField('Repeat', 'Repeat import each ', $repeats));
             }
             $migrateButton = FormAction::create('migrate', _t('ExternalContent.IMPORT', 'Start Importing'))->setAttribute('data-icon', 'arrow-circle-double')->setUseButtonTag(true);
             $fields->addFieldToTab('Root.Import', new LiteralField('MigrateActions', "<div class='Actions'>{$migrateButton->forTemplate()}</div>"));
         }
         $fields->push($hf = new HiddenField("ID"));
         $hf->setValue($id);
         $fields->push($hf = new HiddenField("Version"));
         $hf->setValue(1);
         $actions = new FieldList();
         $actions = CompositeField::create()->setTag('fieldset')->addExtraClass('ss-ui-buttonset');
         $actions = new FieldList($actions);
         // Only show save button if not 'assets' folder
         if ($record->canEdit()) {
             $actions->push(FormAction::create('save', _t('ExternalContent.SAVE', 'Save'))->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'accept')->setUseButtonTag(true));
         }
         if ($isSource && $record->canDelete()) {
             $actions->push(FormAction::create('delete', _t('ExternalContent.DELETE', 'Delete'))->addExtraClass('delete ss-ui-action-destructive')->setAttribute('data-icon', 'decline')->setUseButtonTag(true));
         }
         $form = new Form($this, "EditForm", $fields, $actions);
         if ($record->ID) {
             $form->loadDataFrom($record);
         } else {
             $form->loadDataFrom(array("ID" => "root", "URL" => Director::absoluteBaseURL() . self::$url_segment));
         }
         if (!$record->canEdit()) {
             $form->makeReadonly();
         }
     } else {
         // Create a dummy form
         $fields = new FieldList();
         $form = new Form($this, "EditForm", $fields, new FieldList());
     }
     $form->addExtraClass('cms-edit-form center ss-tabset ' . $this->BaseCSSClasses());
     $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
     $form->setAttribute('data-pjax-fragment', 'CurrentForm');
     $this->extend('updateEditForm', $form);
     return $form;
 }
 public function ExchangeRateSettingsForm()
 {
     $shopConfig = ShopConfig::get()->First();
     if (singleton($this->modelClass)->hasMethod('getCMSValidator')) {
         $detailValidator = singleton($this->modelClass)->getCMSValidator();
         $listField->getConfig()->getComponentByType('GridFieldDetailForm')->setValidator($detailValidator);
     }
     $config = GridFieldConfig_HasManyRelationEditor::create();
     $detailForm = $config->getComponentByType('GridFieldDetailForm')->setValidator(singleton('ExchangeRate')->getCMSValidator());
     if (class_exists('GridFieldSortableRows')) {
         $config->addComponent(new GridFieldSortableRows('SortOrder'));
     }
     $fields = new FieldList($rootTab = new TabSet('Root', $tabMain = new Tab('ExchangeRates', GridField::create('ExchangeRates', 'ExchangeRates', $shopConfig->ExchangeRates(), $config))));
     $actions = new FieldList();
     $actions->push(FormAction::create('saveExchangeRateSettings', _t('GridFieldDetailForm.Save', 'Save'))->setUseButtonTag(true)->addExtraClass('ss-ui-action-constructive')->setAttribute('data-icon', 'add'));
     $form = new Form($this, 'EditForm', $fields, $actions);
     $form->setTemplate('ShopAdminSettings_EditForm');
     $form->setAttribute('data-pjax-fragment', 'CurrentForm');
     $form->addExtraClass('cms-content cms-edit-form center ss-tabset');
     if ($form->Fields()->hasTabset()) {
         $form->Fields()->findOrMakeTab('Root')->setTemplate('CMSTabSet');
     }
     $form->setFormAction(Controller::join_links($this->Link($this->sanitiseClassName($this->modelClass)), 'ExchangeRate/ExchangeRateSettingsForm'));
     $form->loadDataFrom($shopConfig);
     return $form;
 }
Example #26
0
 /**
  * Returns a form for filtering of files and assets gridfield.
  * Result filtering takes place in {@link getList()}.
  *
  * @return Form
  * @see AssetAdmin.js
  */
 public function SearchForm()
 {
     $folder = $this->currentPage();
     $context = $this->getSearchContext();
     $fields = $context->getSearchFields();
     $actions = new FieldList(FormAction::create('doSearch', _t('CMSMain_left_ss.APPLY_FILTER', 'Apply Filter'))->addExtraClass('ss-ui-action-constructive'), Object::create('ResetFormAction', 'clear', _t('CMSMain_left_ss.RESET', 'Reset')));
     $form = new Form($this, 'filter', $fields, $actions);
     $form->setFormMethod('GET');
     $form->setFormAction(Controller::join_links($this->Link('show'), $folder->ID));
     $form->addExtraClass('cms-search-form');
     $form->loadDataFrom($this->getRequest()->getVars());
     $form->disableSecurityToken();
     // This have to match data-name attribute on the gridfield so that the javascript selectors work
     $form->setAttribute('data-gridfield', 'File');
     return $form;
 }
Example #27
0
 public function getEditForm($id = null, $fields = null)
 {
     // TODO Duplicate record fetching (see parent implementation)
     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);
     }
     $memberList = GridField::create('Members', false, Member::get(), $memberListConfig = GridFieldConfig_RecordEditor::create()->addComponent(new GridFieldExportButton()))->addExtraClass("members_grid");
     $memberListConfig->getComponentByType('GridFieldDetailForm')->setValidator(new Member_Validator());
     $groupList = GridField::create('Groups', false, Group::get(), GridFieldConfig_RecordEditor::create());
     $columns = $groupList->getConfig()->getComponentByType('GridFieldDataColumns');
     $columns->setDisplayFields(array('Breadcrumbs' => singleton('Group')->fieldLabel('Title')));
     $fields = new FieldList($root = new TabSet('Root', $usersTab = new Tab('Users', _t('SecurityAdmin.Users', 'Users'), $memberList, new LiteralField('MembersCautionText', sprintf('<p class="caution-remove"><strong>%s</strong></p>', _t('SecurityAdmin.MemberListCaution', 'Caution: Removing members from this list will remove them from all groups and the' . ' database'))), new HeaderField(_t('SecurityAdmin.IMPORTUSERS', 'Import users'), 3), new LiteralField('MemberImportFormIframe', sprintf('<iframe src="%s" id="MemberImportFormIframe" width="100%%" height="250px" border="0">' . '</iframe>', $this->Link('memberimport')))), $groupsTab = new Tab('Groups', singleton('Group')->i18n_plural_name(), $groupList, new HeaderField(_t('SecurityAdmin.IMPORTGROUPS', 'Import groups'), 3), new LiteralField('GroupImportFormIframe', sprintf('<iframe src="%s" id="GroupImportFormIframe" width="100%%" height="250px" border="0">' . '</iframe>', $this->Link('groupimport'))))), new HiddenField('ID', false, 0));
     $root->setTemplate('CMSTabSet');
     // Add roles editing interface
     if (Permission::check('APPLY_ROLES')) {
         $rolesField = GridField::create('Roles', false, PermissionRole::get(), GridFieldConfig_RecordEditor::create());
         $rolesTab = $fields->findOrMakeTab('Root.Roles', _t('SecurityAdmin.TABROLES', 'Roles'));
         $rolesTab->push($rolesField);
     }
     $actionParam = $this->request->param('Action');
     if ($actionParam == 'groups') {
         $groupsTab->addExtraClass('ui-state-selected');
     } elseif ($actionParam == 'users') {
         $usersTab->addExtraClass('ui-state-selected');
     } elseif ($actionParam == 'roles') {
         $rolesTab->addExtraClass('ui-state-selected');
     }
     $actions = new FieldList();
     $form = new Form($this, 'EditForm', $fields, $actions);
     $form->addExtraClass('cms-edit-form');
     $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
     if ($form->Fields()->hasTabset()) {
         $form->Fields()->findOrMakeTab('Root')->setTemplate('CMSTabSet');
     }
     $form->addExtraClass('center ss-tabset cms-tabset ' . $this->BaseCSSClasses());
     $form->setAttribute('data-pjax-fragment', 'CurrentForm');
     $this->extend('updateEditForm', $form);
     return $form;
 }
 public function ListViewForm()
 {
     $params = $this->request->requestVar('q');
     if (($module = $this->request->requestVar('Module')) || !empty($params)) {
         $gridField = $this->getModulesGridField($params, $module);
     } else {
         $gridField = $this->getModuleTypesGridField();
     }
     $listview = new Form($this, 'ListViewForm', new FieldList($gridField), new FieldList());
     //$listview->addExtraClass('cms-edit-form');
     $listview->setTemplate($this->getTemplatesWithSuffix('_ListViewForm'));
     // TODO Can't merge $FormAttributes in template at the moment
     $listview->addExtraClass($this->BaseCSSClasses());
     $listview->setAttribute('data-pjax-fragment', 'ListViewForm');
     $this->extend('updateListView', $listview);
     $listview->disableSecurityToken();
     return $listview;
 }
Example #29
0
 public function ListViewForm()
 {
     $params = $this->request->requestVar('q');
     $list = $this->getList($params, $parentID = $this->request->requestVar('ParentID'));
     $gridFieldConfig = GridFieldConfig::create()->addComponents(new GridFieldSortableHeader(), new GridFieldDataColumns(), new GridFieldPaginator(15));
     if ($parentID) {
         $gridFieldConfig->addComponent(GridFieldLevelup::create($parentID)->setLinkSpec('?ParentID=%d&view=list')->setAttributes(array('data-pjax' => 'ListViewForm,Breadcrumbs')));
     }
     $gridField = new GridField('Page', 'Pages', $list, $gridFieldConfig);
     $columns = $gridField->getConfig()->getComponentByType('GridFieldDataColumns');
     // Don't allow navigating into children nodes on filtered lists
     $fields = array('getTreeTitle' => _t('SiteTree.PAGETITLE', 'Page Title'), 'Created' => _t('SiteTree.CREATED', 'Date Created'), 'LastEdited' => _t('SiteTree.LASTUPDATED', 'Last Updated'));
     $gridField->getConfig()->getComponentByType('GridFieldSortableHeader')->setFieldSorting(array('getTreeTitle' => 'Title'));
     if (!$params) {
         $fields = array_merge(array('listChildrenLink' => ''), $fields);
     }
     $columns->setDisplayFields($fields);
     $columns->setFieldCasting(array('Created' => 'Datetime->Ago', 'LastEdited' => 'Datetime->Ago', 'getTreeTitle' => 'HTMLText'));
     $controller = $this;
     $columns->setFieldFormatting(array('listChildrenLink' => function ($value, &$item) use($controller) {
         $num = $item ? $item->numChildren() : null;
         if ($num) {
             return sprintf('<a class="cms-panel-link list-children-link" data-pjax-target="ListViewForm,Breadcrumbs" href="%s">%s</a>', Controller::join_links($controller->Link(), "?ParentID={$item->ID}&view=list"), $num);
         }
     }, 'getTreeTitle' => function ($value, &$item) use($controller) {
         return '<a class="action-detail" href="' . singleton('CMSPageEditController')->Link('show') . '/' . $item->ID . '">' . $item->TreeTitle . '</a>';
     }));
     $listview = new Form($this, 'ListViewForm', new FieldList($gridField), new FieldList());
     $listview->setAttribute('data-pjax-fragment', 'ListViewForm');
     $this->extend('updateListView', $listview);
     $listview->disableSecurityToken();
     return $listview;
 }