/** * Handles adding a new instance of the grid's model class. * * @param GridField $grid * @param SS_HTTPRequest $request * @throws Exception * @return \GridFieldAddNewMultiClassHandler */ public function handleAdd($grid, $request) { $component = $grid->getConfig()->getComponentByType('GridFieldDetailForm'); if (!$component) { throw new Exception('The ReplicantAddNewButton component requires a detail form component in the grid.'); } $controller = $grid->getForm()->getController(); $className = $grid->getModelClass(); $obj = $className::create(); $handler = new ReplicantAddNewButtonHandler($grid, $component, $obj, $controller); $handler->setTemplate($component->getTemplate()); return $handler; }
/** * * @param GridField $gridField * @param SS_HTTPRequest $request * @return GridFieldDetailForm_ItemRequest */ public function handleItem($gridField, $request) { // Our getController could either give us a true Controller, if this is the top-level GridField. // It could also give us a RequestHandler in the form of GridFieldDetailForm_ItemRequest if this is a // nested GridField. $requestHandler = $gridField->getForm()->getController(); if (is_numeric($request->param('ID'))) { $record = $gridField->getList()->byId($request->param("ID")); } else { $record = Object::create($gridField->getModelClass()); } $handler = $this->getItemRequestHandler($gridField, $record, $requestHandler); // if no validator has been set on the GridField and the record has a // CMS validator, use that. if (!$this->getValidator() && (method_exists($record, 'getCMSValidator') || $record instanceof Object && $record->hasMethod('getCMSValidator'))) { $this->setValidator($record->getCMSValidator()); } return $handler->handleRequest($request, DataModel::inst()); }
/** * If an object ID is set, add the object to the list * * @param GridField $gridField * @param SS_List $dataList * @return SS_List */ public function getManipulatedData(GridField $gridField, SS_List $dataList) { if (!$gridField->State->GridFieldAddRelation) { return $dataList; } $objectID = Convert::raw2sql($gridField->State->GridFieldAddRelation); if ($objectID) { $object = DataObject::get_by_id($dataList->dataclass(), $objectID); if ($object) { if ($this->_item_limit > 0 && $dataList->count() + 1 > $this->_item_limit) { $gridField->getForm()->getController()->getResponse()->addHeader('X-Status', _t('LimitedRelationsGridField.ITEM_LIMIT_REACHED', '_You cannot add any more items, you can only add {count} items. Please remove one then try again.', array('count' => $this->_item_limit))); } else { $dataList->add($object); } } } $gridField->State->GridFieldAddRelation = null; return $dataList; }
/** * Import the current file * @param SS_HTTPRequest $request */ public function import(SS_HTTPRequest $request) { $hasheader = (bool) $request->postVar('HasHeader'); $cleardata = $this->component->getCanClearData() ? (bool) $request->postVar('ClearData') : false; if ($request->postVar('action_import')) { $file = File::get()->byID($request->param('FileID')); if (!$file) { return "file not found"; } $colmap = Convert::raw2sql($request->postVar('mappings')); if ($colmap) { //save mapping to cache $this->cacheMapping($colmap); //do import $results = $this->importFile($file->getFullPath(), $colmap, $hasheader, $cleardata); $this->gridField->getForm()->sessionMessage($results->getMessage(), 'good'); } } $controller = $this->getToplevelController(); $controller->redirectBack(); }
/** * Return the title of the printed page * * @param GridField * * @return array */ public function getTitle(GridField $gridField) { $form = $gridField->getForm(); $currentController = Controller::curr(); $title = ''; if (method_exists($currentController, 'Title')) { $title = $currentController->Title(); } else { if ($currentController->Title) { $title = $currentController->Title; } else { if ($form->Name()) { $title = $form->Name(); } } } if ($fieldTitle = $gridField->Title()) { if ($title) { $title .= " - "; } $title .= $fieldTitle; } return $title; }
/** * Pass control over to the RequestHandler. * * @param GridField $gridField * @param SS_HTTPRequest $request * * @return mixed */ public function handleBulkUpload($gridField, $request) { $controller = $gridField->getForm()->Controller(); $handler = new GridFieldBulkUpload_Request($gridField, $this, $controller); return $handler->handleRequest($request, DataModel::inst()); }
/** * Pass control over to the RequestHandler * loop through the handlers provided in config['actions'] * and find matching url_handlers. * * $url_handlers rule should not use wildcards like '$Action' => '$Action' * but have more specific path defined * * @param GridField $gridField * @param SS_HTTPRequest $request * * @return mixed */ public function handleBulkAction($gridField, $request) { $controller = $gridField->getForm()->Controller(); foreach ($this->config['actions'] as $name => $data) { $handlerClass = $data['handler']; $urlHandlers = Config::inst()->get($handlerClass, 'url_handlers', Config::UNINHERITED); if ($urlHandlers) { foreach ($urlHandlers as $rule => $action) { if ($request->match($rule, false)) { //print_r('matched ' . $handlerClass . ' to ' . $rule); $handler = Injector::inst()->create($handlerClass, $gridField, $this, $controller); return $handler->handleRequest($request, DataModel::inst()); } } } } user_error('Unable to find matching bulk action handler for ' . $request->remaining() . '.', E_USER_ERROR); }
/** * Handles requests to reorder a set of IDs in a specific order. * * @param GridField $grid * @param SS_HTTPRequest $request * @return SS_HTTPResponse */ public function handleReorder($grid, $request) { $list = $grid->getList(); $modelClass = $grid->getModelClass(); if ($list instanceof ManyManyList && !singleton($modelClass)->canView()) { $this->httpError(403); } else { if (!$list instanceof ManyManyList && !singleton($modelClass)->canEdit()) { $this->httpError(403); } } $ids = $request->postVar('order'); $field = $this->getSortField(); if (!is_array($ids)) { $this->httpError(400); } $sortterm = ''; if ($this->extraSortFields) { if (is_array($this->extraSortFields)) { foreach ($this->extraSortFields as $col => $dir) { $sortterm .= "{$col} {$dir}, "; } } else { $sortterm = $this->extraSortFields . ', '; } } $sortterm .= '"' . $this->getSortTable($list) . '"."' . $field . '"'; $items = $list->filter('ID', $ids)->sort($sortterm); // Ensure that each provided ID corresponded to an actual object. if (count($items) != count($ids)) { $this->httpError(404); } // Save any un-comitted changes to the gridfield if (($form = $grid->getForm()) && ($record = $form->getRecord())) { $form->loadDataFrom($request->requestVars(), true); $grid->saveInto($record); } // Populate each object we are sorting with a sort value. $this->populateSortValues($items); // Generate the current sort values. if ($items instanceof ManyManyList) { $current = array(); foreach ($items->toArray() as $record) { // NOTE: _SortColumn0 is the first ->sort() field // used by SS when functions are detected in a SELECT // or CASE WHEN. if (isset($record->_SortColumn0)) { $current[$record->ID] = $record->_SortColumn0; } else { $current[$record->ID] = $record->{$field}; } } } else { $current = $items->map('ID', $field)->toArray(); } // Perform the actual re-ordering. $this->reorderItems($list, $current, $ids); return $grid->FieldHolder(); }
/** * Handles the add action for the given DataObject * * @param $gridFIeld GridFIeld * @param $actionName string * @param $arguments mixed * @param $data array **/ public function handleAction(GridField $gridField, $actionName, $arguments, $data) { if ($actionName == "add") { // Get our submitted fields and object class $dbField = $this->getDataObjectField(); $objClass = $gridField->getModelClass(); $source_class = $this->getSourceClass(); $filter = array(); // Has the user used autocomplete if (isset($data['relationID']) && $data['relationID']) { $id = $data['relationID']; } else { $id = null; } $obj = new $objClass(); // Is this a valid field if (!$obj->hasField($dbField)) { throw new UnexpectedValueException("Invalid field (" . $dbField . ") on " . $obj->ClassName . "."); } // If we have an ID try and get an existing object then // check if we have a copy in items if ($id) { $source_item = $source_class::get()->byID($id); foreach ($this->getFilterFields() as $filter_field) { $filter[$filter_field] = $source_item->{$filter_field}; } } else { // Generate the filter we need to use $string = $data['gridfieldaddbydbfield']; foreach ($this->getFilterFields() as $filter_field) { $filter[$filter_field] = $string; } } // First check if we already have an object or if we need to // create one $existing_obj = $gridField->getList()->filterAny($filter)->first(); if ($existing_obj) { $obj = $existing_obj; } if ($obj->ID && $obj->canEdit()) { // An existing record and can edit, update quantity $curr_qty = $obj->Quantity ? $obj->Quantity : 0; $obj->setCastedField("Quantity", $curr_qty + 1); $id = $gridField->getList()->add($obj); } if (!$obj->ID && $obj->canCreate()) { // If source item not set, try and get one or get a // an existing record if (!$source_item) { $source_item = $source_class::get()->filterAny($filter)->first(); } if ($source_item) { foreach ($this->getSourceFields() as $obj_field => $source_field) { $obj->setCastedField($obj_field, $source_item->{$source_field}); } } else { $obj->setCastedField($this->getCreateField(), $string); } $obj->setCastedField("Quantity", 1); $id = $gridField->getList()->add($obj); } if (!$id) { $gridField->setError(_t("GridFieldAddOrderItem.AddFail", "Unable to save {class} to the database.", "Unable to add the DataObject.", array("class" => get_class($obj))), "error"); } // Finally, issue a redirect to update totals $controller = Controller::curr(); $response = $controller->response; $response->addHeader('X-Pjax', 'Content'); $response->addHeader('X-Reload', true); return $controller->redirect($gridField->getForm()->controller->Link(), 302); } }
public function handleAction(GridField $gridField, $actionName, $arguments, $data) { if ($actionName == 'addapikey') { MemberApiKey::createKey($gridField->getForm()->getRecord()->ID); } }
/** * Return a configured UploadField instance * * @param GridField $gridField Current GridField * @return UploadField Configured UploadField instance */ public function getUploadField(GridField $gridField) { $uploadField = UploadField::create($gridField->Name . "_ImportUploadField", 'Upload CSV')->setForm($gridField->getForm())->setConfig('url', $gridField->Link('importer/upload'))->setConfig('edit_url', $gridField->Link('importer/import'))->setConfig('allowedMaxFileNumber', 1)->setConfig('changeDetection', false)->setConfig('canPreviewFolder', false)->setConfig('canAttachExisting', false)->setConfig('overwriteWarning', false)->setAllowedExtensions(array('csv'))->setFolderName('csvImports')->addExtraClass("import-upload-csv-field"); return $uploadField; }
/** * * @param GridField $gridField * @return string - HTML */ public function getHTMLFragments($gridField) { $dataClass = $gridField->getList()->dataClass(); $forTemplate = new ArrayData(array()); $forTemplate->Fields = new FieldList(); $searchField = new TextField('gridfield_relationsearch', _t('GridField.RelationSearch', "Relation search")); $searchField->setAttribute('data-search-url', Controller::join_links($gridField->Link('search'))); $searchField->setAttribute('placeholder', $this->getPlaceholderText($dataClass)); $searchField->addExtraClass('relation-search no-change-track action_gridfield_relationsearch'); $findAction = new GridField_FormAction($gridField, 'gridfield_relationfind', _t('GridField.Find', "Find"), 'find', 'find'); $findAction->setAttribute('data-icon', 'relationfind'); $findAction->addExtraClass('action_gridfield_relationfind'); $addAction = new GridField_FormAction($gridField, 'gridfield_relationadd', _t('GridField.LinkExisting', "Link Existing"), 'addto', 'addto'); $addAction->setAttribute('data-icon', 'chain--plus'); $addAction->addExtraClass('action_gridfield_relationadd'); // If an object is not found, disable the action if (!is_int($gridField->State->GridFieldAddRelation(null))) { $addAction->setReadonly(true); } $forTemplate->Fields->push($searchField); $forTemplate->Fields->push($findAction); $forTemplate->Fields->push($addAction); if ($form = $gridField->getForm()) { $forTemplate->Fields->setForm($form); } return array($this->targetFragment => $forTemplate->renderWith($this->itemClass)); }
/** * @return Controller */ public function getController() { return $this->grid->getForm()->getController(); }
/** * Handles requests to reorder a set of IDs in a specific order. * * @param GridField $grid * @param SS_HTTPRequest $request * @return SS_HTTPResponse */ public function handleReorder($grid, $request) { if (!$this->immediateUpdate) { $this->httpError(400); } $list = $grid->getList(); $modelClass = $grid->getModelClass(); if ($list instanceof ManyManyList && !singleton($modelClass)->canView()) { $this->httpError(403); } else { if (!$list instanceof ManyManyList && !singleton($modelClass)->canEdit()) { $this->httpError(403); } } // Save any un-committed changes to the gridfield if (($form = $grid->getForm()) && ($record = $form->getRecord())) { $form->loadDataFrom($request->requestVars(), true); $grid->saveInto($record); } // Get records from the `GridFieldEditableColumns` column $data = $request->postVar($grid->getName()); $sortedIDs = $this->getSortedIDs($data); if (!$this->executeReorder($grid, $sortedIDs)) { $this->httpError(400); } Controller::curr()->getResponse()->addHeader('X-Status', rawurlencode('Records reordered.')); return $grid->FieldHolder(); }