/** * 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); } }
/** * Return the payment form */ public function PayForm() { $request = $this->getRequest(); $response = Session::get('EwayResponse'); $months = array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'); $years = range(date('y'), date('y') + 10); //Note: years beginning with 0 might cause issues $amount = $response->Payment->TotalAmount; $amount = number_format($amount / 100, 2); $currency = $response->Payment->CurrencyCode; $fields = new FieldList(HiddenField::create('EWAY_ACCESSCODE', '', $response->AccessCode), TextField::create('PayAmount', 'Amount', $amount . ' ' . $currency)->setDisabled(true), $nameField = TextField::create('EWAY_CARDNAME', 'Card holder'), $numberField = TextField::create('EWAY_CARDNUMBER', 'Card Number'), $expMonthField = DropdownField::create('EWAY_CARDEXPIRYMONTH', 'Expiry Month', array_combine($months, $months)), $expYearField = DropdownField::create('EWAY_CARDEXPIRYYEAR', 'Expiry Year', array_combine($years, $years)), $cvnField = TextField::create('EWAY_CARDCVN', 'CVN Number'), HiddenField::create('FormActionURL', '', $response->FormActionURL)); //Test data if (Director::isDev()) { $nameField->setValue('Test User'); $numberField->setValue('4444333322221111'); $expMonthField->setValue('12'); $expYearField->setValue(date('y') + 1); $cvnField->setValue('123'); } $actions = new FieldList(FormAction::create('', 'Process')); $form = new Form($this, 'PayForm', $fields, $actions); $form->setFormAction($response->FormActionURL); Requirements::javascript(FRAMEWORK_DIR . '/thirdparty/jquery/jquery.js'); Requirements::javascript(THIRDPARTY_DIR . '/jquery-entwine/dist/jquery.entwine-dist.js'); Requirements::javascript('payment-eway/javascript/eway-form.js'); $this->extend('updatePayForm', $form); return $form; }
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; }
public function Form() { $fields = new FieldList(new TextField('Name'), new EmailField('Email'), new TextareaField('Message')); $actions = new FieldList(new FormAction('submit', 'Submit')); $form = new Form($this, 'form', $fields, $actions); $form->setFormAction('/blocks/form'); $form->setFormMethod('POST'); return $form; }
public function updateEditForm(Form $form) { $locale = isset($_REQUEST['locale']) ? $_REQUEST['locale'] : $_REQUEST['Locale']; if (!empty($locale) && i18n::validate_locale($locale) && singleton('SiteConfig')->has_extension('Translatable') && (Translatable::get_allowed_locales() === null || in_array($locale, (array) Translatable::get_allowed_locales(), false)) && $locale != Translatable::get_current_locale()) { $orig = Translatable::get_current_locale(); Translatable::set_current_locale($locale); $formAction = $form->FormAction(); $form->setFormAction($formAction); Translatable::set_current_locale($orig); } }
function Form() { $query = $this->request->getVar("search"); $fields = new FieldList(new TextField("search", "", $query)); $actions = new FieldList($searchaction = new FormAction("index", "Search")); $searchaction->setFullAction(null); $form = new Form($this, "SearchForm", $fields, $actions); $form->setFormAction($this->Link()); $form->setFormMethod("GET"); $form->disableSecurityToken(); return $form; }
/** * Builds the entry form so the user can choose what to export. */ function TranslationForm() { $fields = new FieldList(); $fields->push(new LanguageDropdownField('From', 'From language')); $fields->push(new LanguageDropdownField('To', 'To language')); $fields->push(new CheckboxField('Mangle', 'Mangle with ROT13')); // Create actions for the form $actions = new FieldList(new FormAction("translate", "Translate")); $form = new Form($this, "TranslationForm", $fields, $actions); $form->setFormAction(Director::baseURL() . 'dev/data/translate/EntireSiteTranslator/TranslationForm'); return $form; }
/** * Return a form which sends the user to the first results page. If you want * to customize this form, use your own extension and apply that to the * page. * * @return Form */ public function getGoogleSiteSearchForm() { if ($page = GoogleSiteSearchPage::get()->first()) { $label = Config::inst()->get('GoogleSiteSearchDefaultFormExtension', 'submit_button_label'); $formLabel = Config::inst()->get('GoogleSiteSearchDefaultFormExtension', 'input_label'); $form = new Form($this, 'GoogleSiteSearchForm', new FieldList(new TextField('Search', $formLabel)), new FieldList(new FormAction('doSearch', $label))); $form->setFormMethod('GET'); $form->setFormAction($page->Link()); $form->disableSecurityToken(); $form->loadDataFrom($_GET); return $form; } }
/** * Builds the entry form so the user can choose what to export. */ function ExportForm() { $fields = new FieldList(); // Display available yml files so we can re-export easily. $ymlDest = BASE_PATH . '/' . TestDataController::get_data_dir(); $existingFiles = scandir($ymlDest); $ymlFiles = array(); foreach ($existingFiles as $file) { if (preg_match("/.*\\.yml/", $file)) { $ymlFiles[$file] = $file; } } if ($ymlFiles) { $fields->push(new DropdownField('Reexport', 'Reexport to file (will override any other setting): ', $ymlFiles, '', null, '-- choose file --')); } // Get the list of available DataObjects $dataObjectNames = ClassInfo::subclassesFor('DataObject'); unset($dataObjectNames['DataObject']); sort($dataObjectNames); foreach ($dataObjectNames as $dataObjectName) { // Skip test only classes. $class = singleton($dataObjectName); if ($class instanceof TestOnly) { continue; } // Skip testdata internal class if ($class instanceof TestDataTag) { continue; } // Create a checkbox for including this object in the export file $count = $class::get()->Count(); $fields->push($class = new CheckboxField("Class[{$dataObjectName}]", $dataObjectName . " ({$count})")); $class->addExtraClass('class-field'); // Create an ID range selection input $fields->push($range = new TextField("Range[{$dataObjectName}]", '')); $range->addExtraClass('range-field'); } // Create the "traverse relations" option - whether it should automatically include relation objects even if not explicitly ticked. $fields->push(new CheckboxField('TraverseRelations', 'Traverse relations (implicitly includes objects, for example pulls Groups for Members): ', 1)); // Create the option to include real files. $path = BASE_PATH . '/' . TestDataController::get_data_dir(); $fields->push(new CheckboxField('IncludeFiles', "Copy real files (into {$path}files)", 0)); // Create file name input field $fields->push(new TextField('FileName', 'Name of the output YML file: ', 'output.yml')); // Create actions for the form $actions = new FieldList(new FormAction("export", "Export")); $form = new Form($this, "ExportForm", $fields, $actions); $form->setFormAction(Director::baseURL() . 'dev/data/export/TestDataExporter/ExportForm'); return $form; }
/** * @param Controller $controller * @param string $back_url * @return Form */ public static function buildLoginForm(Controller $controller, $back_url = '') { if (!defined('OPENSTACKID_ENABLED') || OPENSTACKID_ENABLED == false) { $form = MemberAuthenticator::get_login_form($controller); return $form; } else { $back_url = OpenStackIdCommon::cleanBackUrl($back_url); $form = new Form($controller, 'OpenStackIdLoginForm', $fields = new FieldList(), $actions = new FieldList(array(new FormAction('dologin', _t('Member.BUTTONLOGIN', "Log in"))))); $form->addExtraClass('form-fieldless'); $form->setFormAction("/Security/login?BackURL={$back_url}"); $form->setFormMethod('post'); return $form; } }
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'))->removeComponentsByType('GridFieldFilterHeader')); // Validation if (singleton($this->modelClass)->hasMethod('getCMSValidator')) { $detailValidator = singleton($this->modelClass)->getCMSValidator(); $listField->getConfig()->getComponentByType('DynamicTemplateGridFieldDetailForm')->setValidator($detailValidator); } $form = new Form($this, 'EditForm', new FieldList($listField, new HeaderField(_t('DynamicTemplateAdmin.IMPORTTEMPLATE', 'Import template'), 3), new LiteralField('TemplateImportFormIframe', sprintf('<iframe src="%s" id="TemplateImportFormIframe" width="100%%" height="250px" border="0"></iframe>', $this->Link('DynamicTemplate/templateimport')))), new FieldList()); $form->addExtraClass('cms-edit-form cms-panel-padded center'); $form->setTemplate($this->getTemplatesWithSuffix('_EditForm')); $form->setFormAction(Controller::join_links($this->Link($this->sanitiseClassName($this->modelClass)), 'EditForm')); // $form->setAttribute('data-pjax-fragment', 'DTEditForm'); $this->extend('updateEditForm', $form); // $this->getRequest()->addHeader('X-Pjax', 'CurrentForm'); return $form; }
/** * Shows results from the "search" action in a TableListField. * * @return Form */ function ResultsForm($searchCriteria) { if ($searchCriteria instanceof HTTPRequest) { $searchCriteria = $searchCriteria->getVars(); } $summaryFields = $this->getResultColumns($searchCriteria); $className = $this->parentController->resultsTableClassName(); $tf = new $className($this->modelClass, $this->modelClass, $summaryFields); $tf->setCustomQuery($this->getSearchQuery($searchCriteria)); $tf->setPageSize($this->parentController->stat('page_length')); $tf->setShowPagination(true); // @todo Remove records that can't be viewed by the current user $tf->setPermissions(array_merge(array('view', 'export'), TableListField::permissions_for_object($this->modelClass))); // csv export settings (select all columns regardless of user checkbox settings in 'ResultsAssembly') $exportFields = $this->getResultColumns($searchCriteria, false); $tf->setFieldListCsv($exportFields); $url = '<a href=\\"' . $this->Link() . '/$ID/edit\\">$value</a>'; $tf->setFieldFormatting(array_combine(array_keys($summaryFields), array_fill(0, count($summaryFields), $url))); // implemented as a form to enable further actions on the resultset // (serverside sorting, export as CSV, etc) $form = new Form($this, 'ResultsForm', new FieldSet(new HeaderField('SearchResultsHeader', _t('ModelAdmin.SEARCHRESULTS', 'Search Results'), 2), $tf), new FieldSet(new FormAction("goBack", _t('ModelAdmin.GOBACK', "Back")), new FormAction("goForward", _t('ModelAdmin.GOFORWARD', "Forward")))); // Include the search criteria on the results form URL, but not dodgy variables like those below $filteredCriteria = $searchCriteria; unset($filteredCriteria['ctf']); unset($filteredCriteria['url']); unset($filteredCriteria['action_search']); if (isset($filteredCriteria['Investors__PEFirm__IsPECMember']) && !$filteredCriteria['Investors__PEFirm__IsPECMember']) { unset($filteredCriteria['Investors__PEFirm__IsPECMember']); } $form->setFormAction($this->Link() . '/ResultsForm?' . http_build_query($filteredCriteria)); return $form; }
/** * Build snapshot move form. * * @param SS_HTTPRequest $request * @param DNDataArchive|null $dataArchive * * @return Form|SS_HTTPResponse */ public function getMoveForm(SS_HTTPRequest $request, DNDataArchive $dataArchive = null) { $dataArchive = $dataArchive ? $dataArchive : DNDataArchive::get()->byId($request->requestVar('DataArchiveID')); $envs = $dataArchive->validTargetEnvironments(); if (!$envs) { return $this->environment404Response(); } $warningMessage = '<div class="alert alert-warning"><strong>Warning:</strong> This will make the snapshot ' . 'available to people with access to the target environment.<br>By pressing "Change ownership" you ' . 'confirm that you have considered data confidentiality regulations.</div>'; $form = new Form($this, 'MoveForm', new FieldList(new HiddenField('DataArchiveID', null, $dataArchive->ID), new LiteralField('Warning', $warningMessage), new DropdownField('EnvironmentID', 'Environment', $envs->map())), new FieldList(FormAction::create('doMove', 'Change ownership')->addExtraClass('btn'))); $form->setFormAction($this->getCurrentProject()->Link() . '/MoveForm'); 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; }
/** * 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; }
function getEPayForm() { Requirements::javascript("http://www.epay.dk/js/standardwindow.js"); Requirements::javascript(THIRDPARTY_DIR . "/jquery/jquery.js"); $customscript = <<<JS \t\t\tjQuery(document).ready(function(\$) {\t\t\t\t \t\t\t\t\$("form#ePay").submit(function(){ \t\t\t\t\topen_ePay_window(); \t\t\t\t\treturn false; \t\t\t\t}); \t\t\t\t \t\t\t});\t JS; if (Director::isLive()) { $customscript .= <<<JS \t\t\t\tjQuery(document).ready(function(\$) { \t\t\t\t\topen_ePay_window(); //enable for auto-submit \t\t\t\t\t\$("form#ePay").hide(); \t\t\t\t});\t JS; } Requirements::customScript($customscript, 'epayinit'); $controller = new EpaydkPayment_Controller(); //http://tech.epay.dk/ePay-Payment-Window-technical-documentation_9.html $fields = new FieldSet(new HiddenField('merchantnumber', 'Merchant Number', self::$merchant_number), new HiddenField('orderid', 'Order ID', $this->ID), new HiddenField('currency', 'Currency', self::$supported_currencies[$this->Amount->Currency]['code']), new HiddenField('amount', 'Amount', $this->Amount->Amount * 100), new HiddenField('language', 'Language', self::$language), new HiddenField('accepturl', 'Accept URL', Director::absoluteBaseURL() . $controller->Link('accept')), new HiddenField('declineurl', 'Decline URL', Director::absoluteBaseURL() . $controller->Link('decline')), new HiddenField('callbackurl', 'Callback URL', Director::absoluteBaseURL() . $controller->Link('callback')), new HiddenField('instantcallback', 'Instant Callback', 1), new HiddenField('instantcapture', 'Instant Capture', 1), new HiddenField('windowstate', 'Window State', 2), new HiddenField('ownreceipt', 'Own Receipt', 1)); //custom configs if (self::$md5key) { $md5data = $this->generateMD5(); $fields->push(new HiddenField('md5key', 'MD5 Key', $md5data)); } if (self::$limit_card_types) { $fields->push(new HiddenField('cardtype', 'Card Type', self::$limit_card_types)); } if (self::$add_fee) { $fields->push(new HiddenField('addfee', 'Add Fee', 1)); } if (self::$auth_sms) { $fields->push(new HiddenField('authsms', 'Auth SMS', self::$auth_sms)); } if (self::$auth_mail) { $fields->push(new HiddenField('authmail', 'Auth Mail', self::$auth_mail)); } if (self::$google_tracker) { $fields->push(new HiddenField('googletracker', 'Google Tracker', self::$google_tracker)); } if (self::$use3d) { $fields->push(new HiddenField('use3D', 'Use 3D', self::$use3d)); } $actions = new FieldSet($openwindow = new FormAction('openwindow', _t('EpaydkPayment.OPENPAYMENTWINDOW', 'Open the ePay Payment Window'))); $form = new Form($controller, 'ePay', $fields, $actions); $form->setHTMLID('ePay'); $form->setFormAction(self::$submit_url); $form->unsetValidator(); $form->disableSecurityToken(); return $form; }
/** * Form used for renaming a folder * @return {Form} Form to be used for renaming a folder */ public function RenameFolderForm() { $folder = SnippetFolder::get()->byID(intval(str_replace('folder-', '', $this->request->getVar('ID')))); if (!empty($folder) && $folder !== false && $folder->ID != 0) { $fields = new FieldList(new TabSet('Root', new Tab('Main', 'Main', new TextField('Name', _t('SnippetFolder.NAME', '_Name'), null, 150))), new HiddenField('ID', 'ID')); $actions = new FieldList(new FormAction('doRenameFolder', _t('CodeBank.SAVE', '_Save'))); } else { $fields = new FieldList(); $actions = new FieldList(); } $validator = new RequiredFields('Name'); $form = new Form($this, 'RenameFolderForm', $fields, $actions, $validator); $form->addExtraClass('member-profile-form'); //If no parent disable folder if (empty($folder) || $folder === false || $folder->ID == 0) { $form->setMessage(_t('CodeBank.FOLDER_NOT_FOUND', '_Folder could not be found'), 'bad'); } else { $form->loadDataFrom($folder); $form->setFormAction(Controller::join_links($form->FormAction(), '?ID=' . $folder->ID)); } return $form; }
public static function getUploadForm($file, $parentClass, $parentId, $parentField) { if ($file instanceof File && class_exists($parentClass) && is_subclass_of($parentClass, "DataObject")) { $parent = $parentClass::get()->byId($parentId); $fields = new FieldList($uploadField = new UploadField($parentField, 'Upload', $parent)); $uploadField->setCanAttachExisting(false); // Block access to Silverstripe assets library $uploadField->setCanPreviewFolder(false); // Don't show target filesystem folder on upload field $uploadField->relationAutoSetting = false; // Prevents the form thinking the GalleryPage is the underlying object $uploadField->setFolderName('Address Book'); $uploadField->setAllowedMaxFileNumber(1); if ($file instanceof Image) { $uploadField->setAllowedFileCategories('image'); } $actions = new FieldList(new FormAction('submit', 'Save')); $from = new Form(Controller::curr(), 'feFileUploadForm', $fields, $actions, null); $urlParams = array('feclass' => $parentClass, 'fefield' => $parentField, 'feid' => $parentId, 'filesUpload' => true, 'fefileid' => $file->ID, 'fefileclass' => $file->ClassName); // feclass: parentClass, // fefield: parentField, // feid: parentId, // feisUpload: true, // value: "{feclass: " + objClass + ",feid: " + objId + "}" // echo http_build_query($urlParams) . "\n"; $from->setFormAction('home/feFileUploadForm?' . http_build_query($urlParams)); return $from; } }
/** * @return Form */ function SyncForm() { $form = new Form($this, 'SyncForm', new FieldSet(), new FieldSet($btn = new FormAction('doSync', _t('FILESYSTEMSYNC', 'Look for new files')))); $form->addExtraClass('actionparams'); $form->setFormMethod('GET'); $form->setFormAction('dev/tasks/FilesystemSyncTask'); $btn->describe(_t('AssetAdmin_left.ss.FILESYSTEMSYNC_DESC', 'SilverStripe maintains its own database of the files & images stored in your assets/ folder. Click this button to update that database, if files are added to the assets/ folder from outside SilverStripe, for example, if you have uploaded files via FTP.')); return $form; }
/** * Shows results from the "search" action in a TableListField. * * @uses getResultsTable() * * @return Form */ function ResultsForm($searchCriteria) { if ($searchCriteria instanceof SS_HTTPRequest) { $searchCriteria = $searchCriteria->getVars(); } $tf = $this->getResultsTable($searchCriteria); // implemented as a form to enable further actions on the resultset // (serverside sorting, export as CSV, etc) $form = new Form($this, 'ResultsForm', new FieldSet(new HeaderField('SearchResultsHeader', _t('ModelAdmin.SEARCHRESULTS', 'Search Results'), 2), $tf), new FieldSet(new FormAction("goBack", _t('ModelAdmin.GOBACK', "Back")), new FormAction("goForward", _t('ModelAdmin.GOFORWARD', "Forward")))); // Include the search criteria on the results form URL, but not dodgy variables like those below $filteredCriteria = $searchCriteria; unset($filteredCriteria['ctf']); unset($filteredCriteria['url']); unset($filteredCriteria['action_search']); $form->setFormAction($this->Link() . '/ResultsForm?' . http_build_query($filteredCriteria)); return $form; }
/** * 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; }
/** * Build snapshot move form. */ public function getMoveForm($request, $dataArchive = null) { $dataArchive = $dataArchive ? $dataArchive : DNDataArchive::get()->byId($request->requestVar('DataArchiveID')); $envs = $dataArchive->validTargetEnvironments(); if (!$envs) { return new SS_HTTPResponse("Environment '" . Convert::raw2xml($request->latestParam('Environment')) . "' not found.", 404); } $form = new Form($this, 'MoveForm', new FieldList(new HiddenField('DataArchiveID', false, $dataArchive->ID), new LiteralField('Warning', '<p class="text-warning"><strong>Warning:</strong> This will make the snapshot available to people with access to the target environment.<br>By pressing "Change ownership" you confirm that you have considered data confidentiality regulations.</p>'), new DropdownField('EnvironmentID', 'Environment', $envs->map())), new FieldList(FormAction::create('doMove', 'Change ownership')->addExtraClass('btn'))); $form->setFormAction($this->getCurrentProject()->Link() . '/MoveForm'); 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; }
/** * Return a Form instance with fields for the * particular report currently viewed. * * @param string $className Class of the report to fetch * @return Form */ public function getEditForm($className = null) { if (!$className) { return $form = $this->EmptyForm(); } Session::set('currentPage', $className); $fields = new FieldSet(); $actions = new FieldSet(); $reports = SS_Report::get_reports('ReportAdmin'); if (!isset($reports[$className])) { return false; } $report = $reports[$className]; if (!$report || !$report->canView()) { return Security::permissionFailure($this); } $fields = $report->getCMSFields(); $actions = $report->getCMSActions(); $idField = new HiddenField('ID'); $idField->setValue($id); $fields->push($idField); $form = new Form($this, 'EditForm', $fields, $actions); // Include search criteria in the form action so that pagination works $filteredCriteria = array_merge($_GET, $_POST); foreach (array('ID', 'url', 'ajax', 'ctf', 'update', 'action_updatereport', 'SecurityID') as $notAParam) { unset($filteredCriteria[$notAParam]); } $formLink = $this->Link() . '/EditForm'; if ($filteredCriteria) { $formLink .= '?' . http_build_query($filteredCriteria); } $form->setFormAction($formLink); $form->setTemplate('ReportAdminForm'); $form->loadDataFrom($this->request->requestVars()); return $form; }
public function SearchForm() { $searchText = $this->GetSearchTerm() ?: ""; $queryType = $this->GetSearchType() ?: ""; $category = $this->GetCategory() ?: ""; $searchField = new TextField('Search', "Search youtube for:", $searchText); $searchField->setAttribute('placeholder', "Type here"); $fields = new FieldList(new DropdownField('queryType', "Search type:", array('relevance' => 'All Videos', 'viewcount' => 'Most Viewed Videos', 'date' => 'Most recent', 'rating' => 'Top rated'), $queryType), new DropdownField('category', "Category:", $this->GetCategories(), $category), $searchField); $action = new FormAction('YouTubeSearchResults', _t('SearchForm.GO', 'Go')); $action->addExtraClass('btn btn-default btn-search'); $action->useButtonTag = true; $action->setButtonContent('<i class="fa fa-search"></i><span class="text-hide">Search</span>'); $actions = new FieldList($action); $form = new Form($this, 'YouTubeSearchForm', $fields, $actions); $form->setFormMethod('GET'); $form->setFormAction($this->Link() . ""); $form->disableSecurityToken(); return $form; }
/** * Shows state which is allowed to be modified while a test session is in progress. */ public function ProgressForm() { $fields = $this->getBaseFields(); $form = new Form($this, 'ProgressForm', $fields, new FieldList(new FormAction('set', 'Set testing state'))); $form->setFormAction($this->Link('set')); $this->extend('updateProgressForm', $form); return $form; }
function done() { $unsubscribeRecordIDs = $this->urlParams['IDs']; $hash = $this->urlParams['ID']; if ($unsubscribeRecordIDs) { $fields = new FieldList(new HiddenField("UnsubscribeRecordIDs", "", $unsubscribeRecordIDs), new HiddenField("Hash", "", $hash), new LiteralField("ResubscribeText", "Click the \"Resubscribe\" if you unsubscribed by accident and want to re-subscribe")); $actions = new FieldList(new FormAction("resubscribe", "Resubscribe")); $form = new Form($this, "ResubscribeForm", $fields, $actions); $form->setFormAction($this->Link('resubscribe')); $mailinglists = $this->getMailingListsByUnsubscribeRecords($unsubscribeRecordIDs); if ($mailinglists && $mailinglists->count()) { $listTitles = ""; foreach ($mailinglists as $list) { $listTitles .= "<li>" . $list->Title . "</li>"; } $recipient = $this->getRecipient(); $title = $recipient->FirstName ? $recipient->FirstName : $recipient->Email; $content = sprintf(_t('Newsletter.UNSUBSCRIBEFROMLISTSSUCCESS', '<h3>Thank you, %s.</h3><br />You will no longer receive: %s.'), $title, "<ul>" . $listTitles . "</ul>"); } else { $content = _t('Newsletter.UNSUBSCRIBESUCCESS', 'Thank you.<br />You have been unsubscribed successfully'); } } return $this->customise(array('Title' => _t('UNSUBSCRIBEDTITLE', 'Unsubscribed'), 'Content' => $content, 'Form' => $form))->renderWith('Page'); }
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; }
/** * Generate a CSV import form for a single {@link DataObject} subclass. * * @return Form */ public function ImportForm() { $modelName = $this->modelClass; // check if a import form should be generated if (!$this->showImportForm || is_array($this->showImportForm) && !in_array($modelName, $this->showImportForm)) { return false; } $importers = $this->getModelImporters(); if (!$importers || !isset($importers[$modelName])) { return false; } if (!singleton($modelName)->canCreate(Member::currentUser())) { return false; } $fields = new FieldList(new HiddenField('ClassName', _t('ModelAdmin.CLASSTYPE'), $modelName), new FileField('_CsvFile', false)); // get HTML specification for each import (column names etc.) $importerClass = $importers[$modelName]; $importer = new $importerClass($modelName); $spec = $importer->getImportSpec(); $specFields = new ArrayList(); foreach ($spec['fields'] as $name => $desc) { $specFields->push(new ArrayData(array('Name' => $name, 'Description' => $desc))); } $specRelations = new ArrayList(); foreach ($spec['relations'] as $name => $desc) { $specRelations->push(new ArrayData(array('Name' => $name, 'Description' => $desc))); } $specHTML = $this->customise(array('ModelName' => Convert::raw2att($modelName), 'Fields' => $specFields, 'Relations' => $specRelations))->renderWith('ModelAdmin_ImportSpec'); $fields->push(new LiteralField("SpecFor{$modelName}", $specHTML)); $fields->push(new CheckboxField('EmptyBeforeImport', _t('ModelAdmin.EMPTYBEFOREIMPORT', 'Replace data'), false)); $actions = new FieldList(new FormAction('import', _t('ModelAdmin.IMPORT', 'Import from CSV'))); $form = new Form($this, "ImportForm", $fields, $actions); $form->setFormAction(Controller::join_links($this->Link($this->sanitiseClassName($this->modelClass)), 'ImportForm')); $this->extend('updateImportForm', $form); return $form; }
/** * Gets the form instance for a record. * * @param GridField $grid * @param DataObjectInterface $record * @return Form */ public function getForm(GridField $grid, DataObjectInterface $record) { $fields = $this->getFields($grid, $record); $form = new Form($this, null, $fields, new FieldList()); $form->loadDataFrom($record); $form->setFormAction(Controller::join_links($grid->Link(), 'editable/form', $record->ID)); return $form; }