public function getManipulatedData(GridField $gridField, SS_List $list)
 {
     if (!$list instanceof RelationList) {
         user_error('GridFieldManyRelationHandler requires the GridField to have a RelationList. Got a ' . get_class($list) . ' instead.', E_USER_WARNING);
     }
     $state = $this->getState($gridField);
     // We don't use setupState() as we need the list
     if ($state->FirstTime) {
         $state->RelationVal = array_values($list->getIdList()) ?: array();
     }
     if (!$state->ShowingRelation && $this->useToggle) {
         return $list;
     }
     $query = clone $list->dataQuery();
     try {
         $query->removeFilterOn($this->cheatList->getForeignIDFilter($list));
     } catch (InvalidArgumentException $e) {
         /* NOP */
     }
     $orgList = $list;
     $list = new DataList($list->dataClass());
     $list = $list->setDataQuery($query);
     if ($orgList instanceof ManyManyList) {
         $joinTable = $this->cheatManyList->getJoinTable($orgList);
         $baseClass = ClassInfo::baseDataClass($list->dataClass());
         $localKey = $this->cheatManyList->getLocalKey($orgList);
         $query->leftJoin($joinTable, "\"{$joinTable}\".\"{$localKey}\" = \"{$baseClass}\".\"ID\"");
         $list = $list->setDataQuery($query);
     }
     return $list;
 }
 public function getCMSFields()
 {
     $fields = parent::getCMSFields();
     // Remove MCListSegment GridField Tab And Manually Manage
     $fields->removeByName("MCListSegments");
     // Manually Manage Creation of MCListSegments Based on Selected MCLists
     if (empty($this->owner->ID)) {
         $lists = new DataList("MCList");
         if ($lists->count() > 1) {
             $fields->addFieldToTab('Root.Main', new LiteralField('_AffectedMCListsTitle', '<h2>Affected MailChimp Lists</h2>'));
             $map = $lists->map("ID", "Name");
             $listIDs = new CheckboxSetField('_AffectedMCListIDs', 'Which MailChimp List(s) Does This Event Relate To', $map);
             $listIDs->setDefaultItems(array_keys($map->toArray()));
         } else {
             if ($lists->count() == 1) {
                 $listIDs = new HiddenField('_AffectedMCListIDs', 'Which MailChimp List(s) Does This Event Relate To', $lists->first()->ID);
             } else {
                 $listIDs = new HiddenField('_AffectedMCListIDs', 'Which MailChimp List(s) Does This Event Relate To', 0);
             }
         }
         $fields->addFieldToTab('Root.Main', $listIDs);
     }
     // Configure Attendees Gridfield
     $gf = $fields->fieldByName('Root.Attendees.Attendees');
     if (is_object($gf) && $gf->exists()) {
         $gf->setList($this->getMyManyManyComponents('Attendees'));
         $config = $gf->getConfig();
         $config->removeComponentsByType('GridfieldAddNewButton');
     }
     return $fields;
 }
 /**
  * If HideUnmatchedFilters is on then remove all filters which are not found in the items by their 'AssociatedFilters' relationship.
  *
  * @param \DataList $filters list of GridListFilter models
  * @param array     $parameters
  * @return \ArrayList
  */
 public function constrainGridListFilters(&$filters, &$parameters = [])
 {
     $out = new \ArrayList();
     if ($this()->{self::SingleFieldName}) {
         $ids = $filters->column('ID');
         if (count($ids)) {
             $items = $this()->GridListItems();
             // this is where we keep track of GridListFilters which have been found on items where ID is the key
             $foundFilters = array_combine($ids, array_fill(0, count($ids), false));
             foreach ($foundFilters as $filterID => &$found) {
                 /** @var \Page|Model $item */
                 foreach ($items as $item) {
                     if ($item->hasExtension(HasGridListFilters::class_name())) {
                         if ($itemFilters = $item->{HasGridListFilters::relationship_name()}()->column('ID')) {
                             if (in_array($filterID, $itemFilters)) {
                                 $found = true;
                                 break;
                             }
                         }
                     }
                 }
             }
             foreach ($filters as $filter) {
                 if (isset($foundFilters[$filter->ID])) {
                     $out->push($filter);
                 }
             }
             $filters = $out;
         }
     }
 }
 public function testNoSpecificColumnNamesSubclassDataObjectQuery()
 {
     // This queries all columns from base table and subtable
     $playerList = new DataList('DataObjectTest_SubTeam');
     // Should be a left join.
     $this->assertEquals(1, preg_match($this->normaliseSQL('/SELECT DISTINCT .* LEFT JOIN .* /'), $this->normaliseSQL($playerList->sql($parameters))));
 }
	public function run($request) {
		$pages = 0;
		$links = 0;

		$linkedPages = new DataList('SiteTree');
		$linkedPages->innerJoin('SiteTree_LinkTracking', '"SiteTree_LinkTracking"."SiteTreeID" = "SiteTree"."ID"');
		if($linkedPages) foreach($linkedPages as $page) {
			$tracking = DB::query(sprintf('SELECT "ChildID", "FieldName" FROM "SiteTree_LinkTracking" WHERE "SiteTreeID" = %d', $page->ID))->map();

			foreach($tracking as $childID => $fieldName) {
				$linked = DataObject::get_by_id('SiteTree', $childID);
				
				// TOOD: Replace in all HTMLText fields
				$page->Content = preg_replace (
					"/href *= *([\"']?){$linked->URLSegment}\/?/i",
					"href=$1[sitetree_link id={$linked->ID}]",
					$page->Content,
					-1,
					$replaced
				);
				
				if($replaced) {
					$links += $replaced;
				}
			}
			
			$page->write();
			$pages++;
		}
		
		echo "Rewrote $links link(s) on $pages page(s) to use shortcodes.\n";
	}
 public function LastUpdated()
 {
     $elements = new DataList($this->dataClass);
     $lastUpdated = new SS_Datetime('LastUpdated');
     $lastUpdated->setValue($elements->max('LastEdited'));
     return $lastUpdated;
 }
 public function filter(DataList $list)
 {
     $groupids = array(0);
     if ($member = $this->getMember()) {
         $groupids = $groupids + $member->Groups()->map('ID', 'ID')->toArray();
     }
     return $list->filter("GroupID", $groupids);
 }
 /**
  * Overloading ManyManyList removeByID Rather Then remove() as That Just Calls removeByID()
  * Remove the given item from this list.
  * Note that for a ManyManyList, the item is never actually deleted, only the join table is affected
  * @param $itemID The item it
  */
 public function removeByID($itemID)
 {
     parent::removeByID($itemID);
     // Get Item Object Itself Based on $itemID
     $dl = new DataList($this->dataClass);
     // Must Include Table Prefix To Prevent "Column 'ID' in where clause is ambiguous" Error
     $item = $dl->where("\"" . $this->dataClass . "\".\"ID\" = '" . $itemID . "'")->first();
     $this->onUnlink($item);
 }
 public static function filter(DataList $list, $member = null)
 {
     $now = date('Y-m-d H:i:s');
     $nowminusone = date('Y-m-d H:i:s', strtotime("-1 day"));
     $groupids = array(0);
     if ($member) {
         $groupids = array_merge($member->Groups()->map('ID', 'ID')->toArray(), $groupids);
     }
     return $list->where("(\"SpecificPrice\".\"StartDate\" IS NULL) OR (\"SpecificPrice\".\"StartDate\" < '{$now}')")->where("(\"SpecificPrice\".\"EndDate\" IS NULL) OR (\"SpecificPrice\".\"EndDate\" > '{$nowminusone}')")->filter("GroupID", $groupids);
 }
 /**
  * takes a DataList of Rateable DataObjects and sorts them by their average score 
  * @param DataList $list
  * @return ArrayList
  **/
 public function sortByRating(DataList $list, $dir = 'DESC')
 {
     $items = new ArrayList($list->toArray());
     foreach ($items as $item) {
         $score = $item->getAverageScore();
         $item->Score = $score ? $score : 0;
         $item->Title = $item->Title;
     }
     return $items->sort('Score', $dir);
 }
 /**
  * Add records to the list.
  */
 protected function processAll($filepath, $preview = false)
 {
     $iterator = $this->getSource()->getIterator();
     $results = new BetterBulkLoader_Result();
     foreach ($iterator as $record) {
         if ($id = $this->processRecord($record, $this->columnMap, $results, $preview)) {
             $this->list->add($id);
         }
     }
     return $results;
 }
 public function onBeforeWrite()
 {
     // If there is no URLSegment set, generate one from Title
     if ((!$this->URLSegment || $this->URLSegment == 'new-product') && $this->Title != 'New Product') {
         $siteTree = DataList::create('SiteTree')->first();
         $this->URLSegment = $siteTree->generateURLSegment($this->Title);
     } else {
         if ($this->isChanged('URLSegment')) {
             // Make sure the URLSegment is valid for use in a URL
             $segment = preg_replace('/[^A-Za-z0-9]+/', '-', $this->URLSegment);
             $segment = preg_replace('/-+/', '-', $segment);
             // If after sanitising there is no URLSegment, give it a reasonable default
             if (!$segment) {
                 $segment = "product-{$this->ID}";
             }
             $this->URLSegment = $segment;
         }
     }
     // Ensure that this object has a non-conflicting URLSegment value.
     $count = 2;
     while ($this->LookForExistingURLSegment($this->URLSegment)) {
         $this->URLSegment = preg_replace('/-[0-9]+$/', null, $this->URLSegment) . '-' . $count;
         $count++;
     }
     parent::onBeforeWrite();
 }
Пример #13
0
 public function scaffoldFormField($title = null, $params = null)
 {
     if (empty($this->object)) {
         return null;
     }
     $relationName = substr($this->name, 0, -2);
     $hasOneClass = $this->object->hasOneComponent($relationName);
     if (empty($hasOneClass)) {
         return null;
     }
     $hasOneSingleton = singleton($hasOneClass);
     if ($hasOneSingleton instanceof File) {
         $field = new UploadField($relationName, $title);
         if ($hasOneSingleton instanceof Image) {
             $field->setAllowedFileCategories('image/supported');
         }
         return $field;
     }
     // Build selector / numeric field
     $titleField = $hasOneSingleton->hasField('Title') ? "Title" : "Name";
     $list = DataList::create($hasOneClass);
     // Don't scaffold a dropdown for large tables, as making the list concrete
     // might exceed the available PHP memory in creating too many DataObject instances
     if ($list->count() < 100) {
         $field = new DropdownField($this->name, $title, $list->map('ID', $titleField));
         $field->setEmptyString(' ');
     } else {
         $field = new NumericField($this->name, $title);
     }
     return $field;
 }
 public function getCMSFields()
 {
     $fields = new FieldList();
     $fields->push(new TabSet('Root', new Tab('Main', _t('SiteTree.TABMAIN', 'Main'), new TextField('Title', _t('UniadsObject.db_Title', 'Title')))));
     if ($this->ID) {
         $previewLink = Director::absoluteBaseURL() . 'admin/' . UniadsAdmin::config()->url_segment . '/UniadsObject/preview/' . $this->ID;
         $fields->addFieldToTab('Root.Main', new ReadonlyField('Impressions', _t('UniadsObject.db_Impressions', 'Impressions')), 'Title');
         $fields->addFieldToTab('Root.Main', new ReadonlyField('Clicks', _t('UniadsObject.db_Clicks', 'Clicks')), 'Title');
         $fields->addFieldsToTab('Root.Main', array(DropdownField::create('CampaignID', _t('UniadsObject.has_one_Campaign', 'Campaign'), DataList::create('UniadsCampaign')->map())->setEmptyString(_t('UniadsObject.Campaign_none', 'none')), DropdownField::create('ZoneID', _t('UniadsObject.has_one_Zone', 'Zone'), DataList::create('UniadsZone')->map())->setEmptyString(_t('UniadsObject.Zone_select', 'select one')), new NumericField('Weight', _t('UniadsObject.db_Weight', 'Weight (controls how often it will be shown relative to others)')), new TextField('TargetURL', _t('UniadsObject.db_TargetURL', 'Target URL')), new Treedropdownfield('InternalPageID', _t('UniadsObject.has_one_InternalPage', 'Internal Page Link'), 'Page'), new CheckboxField('NewWindow', _t('UniadsObject.db_NewWindow', 'Open in a new Window')), $file = new UploadField('File', _t('UniadsObject.has_one_File', 'Advertisement File')), $AdContent = new TextareaField('AdContent', _t('UniadsObject.db_AdContent', 'Advertisement Content')), $Starts = new DateField('Starts', _t('UniadsObject.db_Starts', 'Starts')), $Expires = new DateField('Expires', _t('UniadsObject.db_Expires', 'Expires')), new NumericField('ImpressionLimit', _t('UniadsObject.db_ImpressionLimit', 'Impression Limit')), new CheckboxField('Active', _t('UniadsObject.db_Active', 'Active')), new LiteralField('Preview', '<a href="' . $previewLink . '" target="_blank">' . _t('UniadsObject.Preview', 'Preview this advertisement') . "</a>")));
         $app_categories = File::config()->app_categories;
         $file->setFolderName($this->config()->files_dir);
         $file->getValidator()->setAllowedMaxFileSize(array('*' => $this->config()->max_file_size));
         $file->getValidator()->setAllowedExtensions(array_merge($app_categories['image'], $app_categories['flash']));
         $AdContent->setRows(10);
         $AdContent->setColumns(20);
         $Starts->setConfig('showcalendar', true);
         $Starts->setConfig('dateformat', i18n::get_date_format());
         $Starts->setConfig('datavalueformat', 'yyyy-MM-dd');
         $Expires->setConfig('showcalendar', true);
         $Expires->setConfig('dateformat', i18n::get_date_format());
         $Expires->setConfig('datavalueformat', 'yyyy-MM-dd');
         $Expires->setConfig('min', date('Y-m-d', strtotime($this->Starts ? $this->Starts : '+1 days')));
     }
     $this->extend('updateCMSFields', $fields);
     return $fields;
 }
 public function search($request)
 {
     $list = DataList::create($this->getConfig('classToSearch'));
     $params = array();
     $searchFields = $this->getConfig('searchFields');
     foreach ($searchFields as $searchField) {
         $name = strpos($searchField, ':') !== false ? $searchField : "{$searchField}:partialMatch";
         $params[$name] = $request->getVar('term');
     }
     $start = (int) $request->getVar('id') ? (int) $request->getVar('id') * $this->getConfig('resultsLimit') : 0;
     $list = $list->filterAny($params)->exclude($this->getConfig('excludes'));
     $filter = $this->getConfig('filter');
     if (count($filter) > 0) {
         $list = $list->filter($filter);
     }
     $total = $list->count();
     $results = $list->sort(strtok($searchFields[0], ':'), 'ASC')->limit($this->getConfig('resultsLimit'), $start);
     $return = array('list' => array(), 'total' => $total);
     $originalSourceFileComments = Config::inst()->get('SSViewer', 'source_file_comments');
     Config::inst()->update('SSViewer', 'source_file_comments', false);
     foreach ($results as $object) {
         $return['list'][] = array('id' => $object->ID, 'resultsContent' => html_entity_decode(SSViewer::fromString($this->getConfig('resultsFormat'))->process($object)), 'selectionContent' => SSViewer::fromString($this->getConfig('selectionFormat'))->process($object));
     }
     Config::inst()->update('SSViewer', 'source_file_comments', $originalSourceFileComments);
     return Convert::array2json($return);
 }
 public function __construct($record, $name, $parent)
 {
     $this->record = $record;
     $this->name = $name;
     $this->parent = $parent;
     parent::__construct($record->ClassName);
 }
 public function doSearch($gridField, $request)
 {
     $dataClass = $gridField->getList()->dataClass();
     $allList = $this->searchList ? $this->searchList : DataList::create($dataClass);
     $searchFields = $this->getSearchFields() ? $this->getSearchFields() : $this->scaffoldSearchFields($dataClass);
     if (!$searchFields) {
         throw new LogicException(sprintf('GridFieldAddExistingAutocompleter: No searchable fields could be found for class "%s"', $dataClass));
     }
     $params = array();
     foreach ($searchFields as $searchField) {
         $name = strpos($searchField, ':') !== FALSE ? $searchField : "{$searchField}:StartsWith";
         $params[$name] = $request->getVar('gridfield_relationsearch');
     }
     if (!$gridField->getList() instanceof UnsavedRelationList) {
         $allList = $allList->subtract($gridField->getList());
     }
     $results = $allList->filterAny($params)->sort(strtok($searchFields[0], ':'), 'ASC')->limit($this->getResultsLimit());
     $json = array();
     $originalSourceFileComments = Config::inst()->get('SSViewer', 'source_file_comments');
     Config::inst()->update('SSViewer', 'source_file_comments', false);
     foreach ($results as $result) {
         $json[$result->ID] = html_entity_decode(SSViewer::fromString($this->resultsFormat)->process($result));
     }
     Config::inst()->update('SSViewer', 'source_file_comments', $originalSourceFileComments);
     return Convert::array2json($json);
 }
Пример #18
0
 public function __construct(CalendarEvent $event)
 {
     $this->event = $event;
     $this->datetimeClass = $event->Parent()->getDateTimeClass();
     $this->eventClass = $event->Parent()->getEventClass();
     $relation = $event->Parent()->getDateToEventRelation();
     if ($datetime = DataList::create($this->datetimeClass)->where("{$relation} = {$event->ID}")->first()) {
         $this->ts = strtotime($datetime->StartDate);
     }
     if ($event->CustomRecursionType == 2) {
         if ($days_of_week = $event->getManyManyComponents('RecurringDaysOfWeek')) {
             foreach ($days_of_week as $day) {
                 $this->allowedDaysOfWeek[] = $day->Value;
             }
         }
     } else {
         if ($event->CustomRecursionType == 3) {
             if ($days_of_month = $event->getManyManyComponents('RecurringDaysOfMonth')) {
                 foreach ($days_of_month as $day) {
                     $this->allowedDaysOfMonth[] = $day->Value;
                 }
             }
         }
     }
     if ($exceptions = $event->getComponents('Exceptions')) {
         foreach ($exceptions as $exception) {
             $this->exceptions[] = $exception->ExceptionDate;
         }
     }
 }
Пример #19
0
 public function getMembers()
 {
     //make sure members exist.
     if (DataList::create('Member')->count() >= 1) {
         return DataList::create('Member');
     }
 }
 /**
  * Generates a unique URLSegment from the title.
  *
  * @param int $increment
  *
  * @return string
  */
 public function generateURLSegment($increment = null)
 {
     $filter = new URLSegmentFilter();
     $this->owner->URLSegment = $filter->filter($this->owner->Title);
     if (is_int($increment)) {
         $this->owner->URLSegment .= '-' . $increment;
     }
     // Postgres use '' instead of 0 as an emtpy blog ID
     // Without this all the tests fail
     if (!$this->owner->BlogID) {
         $this->owner->BlogID = 0;
     }
     $duplicate = DataList::create($this->owner->ClassName)->filter(array('URLSegment' => $this->owner->URLSegment, 'BlogID' => $this->owner->BlogID));
     if ($this->owner->ID) {
         $duplicate = $duplicate->exclude('ID', $this->owner->ID);
     }
     if ($duplicate->count() > 0) {
         if (is_int($increment)) {
             $increment += 1;
         } else {
             $increment = 0;
         }
         $this->owner->generateURLSegment((int) $increment);
     }
     return $this->owner->URLSegment;
 }
Пример #21
0
 public function __construct($name, $title = null, $value = "")
 {
     // naming with underscores to prevent values from actually being saved somewhere
     $this->fieldType = new OptionsetField("{$name}[Type]", _t('HtmlEditorField.LINKTO', 'Link to'), array('Internal' => _t('HtmlEditorField.LINKINTERNAL', 'Page on the site'), 'External' => _t('HtmlEditorField.LINKEXTERNAL', 'Another website'), 'Email' => _t('HtmlEditorField.LINKEMAIL', 'Email address'), 'File' => _t('HtmlEditorField.LINKFILE', 'Download a file')), 'Internal');
     $this->fieldLink = new CompositeField($this->internalField = WTTreeDropdownField::create("{$name}[Internal]", _t('HtmlEditorField.Internal', 'Internal'), 'SiteTree', 'ID', 'Title', true), $this->externalField = TextField::create("{$name}[External]", _t('HtmlEditorField.URL', 'URL'), 'http://'), $this->emailField = EmailField::create("{$name}[Email]", _t('HtmlEditorField.EMAIL', 'Email address')), $this->fileField = WTTreeDropdownField::create("{$name}[File]", _t('HtmlEditorField.FILE', 'File'), 'File', 'ID', 'Title', true), $this->extraField = TextField::create("{$name}[Extra]", 'Extra(optional)')->setDescription('Appended to url. Use to add sub-urls/actions or query string to the url, e.g. ?param=value'), $this->anchorField = TextField::create("{$name}[Anchor]", 'Anchor (optional)'), $this->targetBlankField = CheckboxField::create("{$name}[TargetBlank]", _t('HtmlEditorField.LINKOPENNEWWIN', 'Open link in a new window?')));
     if ($linkableDataObjects = WTLink::get_data_object_types()) {
         if (!($objects = self::$linkable_data_objects)) {
             $objects = array();
             foreach ($linkableDataObjects as $className) {
                 $classObjects = array();
                 //set the format for DO value -> ClassName-ID
                 foreach (DataList::create($className) as $object) {
                     $classObjects[$className . '-' . $object->ID] = $object->Title;
                 }
                 if (!empty($classObjects)) {
                     $objects[singleton($className)->i18n_singular_name()] = $classObjects;
                 }
             }
         }
         if (count($objects)) {
             $this->fieldType->setSource(array_merge($this->fieldType->getSource(), array('DataObject' => _t('WTLinkField.LINKDATAOBJECT', 'Data Object'))));
             $this->fieldLink->insertBefore("{$name}[Extra]", $this->dataObjectField = GroupedDropdownField::create("{$name}[DataObject]", _t('WTLinkField.LINKDATAOBJECT', 'Link to a Data Object'), $objects));
         }
         self::$linkable_data_objects = $objects;
     }
     $this->extraField->addExtraClass('no-hide');
     $this->anchorField->addExtraClass('no-hide');
     $this->targetBlankField->addExtraClass('no-hide');
     parent::__construct($name, $title, $value);
 }
 /**
  * Generates a unique URLSegment from the title.
  *
  * @param int $increment
  *
  * @return string
  */
 public function generateURLSegment($increment = null)
 {
     $filter = new URLSegmentFilter();
     // Setting this to on. Because of the UI flow, it would be quite a lot of work
     // to support turning this off. (ie. the add by title flow would not work).
     // If this becomes a problem we can approach it then.
     // @see https://github.com/silverstripe/silverstripe-blog/issues/376
     $filter->setAllowMultibyte(true);
     $this->owner->URLSegment = $filter->filter($this->owner->Title);
     if (is_int($increment)) {
         $this->owner->URLSegment .= '-' . $increment;
     }
     // Postgres use '' instead of 0 as an emtpy blog ID
     // Without this all the tests fail
     if (!$this->owner->BlogID) {
         $this->owner->BlogID = 0;
     }
     $duplicate = DataList::create($this->owner->ClassName)->filter(array('URLSegment' => $this->owner->URLSegment, 'BlogID' => $this->owner->BlogID));
     if ($this->owner->ID) {
         $duplicate = $duplicate->exclude('ID', $this->owner->ID);
     }
     if ($duplicate->count() > 0) {
         if (is_int($increment)) {
             $increment += 1;
         } else {
             $increment = 0;
         }
         $this->owner->generateURLSegment((int) $increment);
     }
     return $this->owner->URLSegment;
 }
 public static function parse_flickr($arguments, $caption = null, $parser = null)
 {
     // first things first, if we dont have a video ID, then we don't need to
     // go any further
     if (empty($arguments['id'])) {
         return;
     }
     $customise = array();
     /*** SET DEFAULTS ***/
     $fp = DataList::create('FlickrPhoto')->where('FlickrID=' . $arguments['id'])->first();
     if (!$fp) {
         return '';
     }
     $customise['FlickrImage'] = $fp;
     //set the caption
     if ($caption === null || $caption === '') {
         if (isset($arguments['caption'])) {
             $caption = $arguments['caption'];
         }
     }
     $customise['Caption'] = $caption ? Convert::raw2xml($caption) : $fp->Title;
     $customise['Position'] = !empty($arguments['position']) ? $arguments['position'] : 'center';
     $customise['Small'] = true;
     if ($customise['Position'] == 'center') {
         $customise['Small'] = false;
     }
     $fp = null;
     //overide the defaults with the arguments supplied
     $customise = array_merge($customise, $arguments);
     //get our YouTube template
     $template = new SSViewer('ShortCodeFlickrPhoto');
     //return the customised template
     return $template->process(new ArrayData($customise));
 }
 public function scaffoldFormField($title = null, $params = null)
 {
     if (empty($this->object)) {
         return null;
     }
     $relationName = substr($this->name, 0, -2);
     $hasOneClass = $this->object->hasOneComponent($relationName);
     if ($hasOneClass && singleton($hasOneClass) instanceof Image) {
         $field = new UploadField($relationName, $title);
         $field->getValidator()->setAllowedExtensions(array('jpg', 'jpeg', 'png', 'gif'));
     } elseif ($hasOneClass && singleton($hasOneClass) instanceof File) {
         $field = new UploadField($relationName, $title);
     } else {
         $titleField = singleton($hasOneClass)->hasField('Title') ? "Title" : "Name";
         $list = DataList::create($hasOneClass);
         // Don't scaffold a dropdown for large tables, as making the list concrete
         // might exceed the available PHP memory in creating too many DataObject instances
         if ($list->count() < 100) {
             $field = new DropdownField($this->name, $title, $list->map('ID', $titleField));
             $field->setEmptyString(' ');
         } else {
             $field = new NumericField($this->name, $title);
         }
     }
     return $field;
 }
 /**
  * Handles the given action context.
  * 
  * @param GridField $gridField  GridField to handle action for
  * @param string    $actionName Name of the action to handle
  * @param array     $arguments  Arguments
  * @param array     $data       Post data to handle
  * 
  * @return string
  * 
  * @author Sebastian Diel <*****@*****.**>
  * @since 14.03.2013
  */
 public function handleAction(GridField $gridField, $actionName, $arguments, $data)
 {
     if ($actionName == 'addsubobject') {
         $recordID = $data['SubObjectParentID'];
         $subObjectID = $data[$gridField->getModelClass() . 'SubObjects'][$recordID];
         $list = $gridField->getList();
         $parent = DataObject::get($gridField->getModelClass())->byID($recordID);
         $subObject = DataObject::get($this->targetClassName)->byID($subObjectID);
         if ($subObject instanceof $this->targetClassName && $subObject->exists()) {
             $this->subList->add($subObject);
         }
     } elseif ($actionName == 'removesubobject' || $actionName == 'activatesubobject' || $actionName == 'deactivatesubobject' || $actionName == 'defaultsubobject' || $actionName == 'undefaultsubobject') {
         $recordID = $data['SubObjectParentID'];
         $subObjectID = $data['SubObjectID'];
         $list = $gridField->getList();
         $parent = DataObject::get($gridField->getModelClass())->byID($recordID);
         $subObject = DataObject::get($this->targetClassName)->byID($subObjectID);
         if ($subObject instanceof $this->targetClassName && $subObject->exists()) {
             if ($actionName == 'defaultsubobject' || $actionName == 'undefaultsubobject') {
                 $this->subList->add($subObject, array('IsDefault' => $actionName == 'defaultsubobject'));
             } elseif ($actionName == 'activatesubobject' || $actionName == 'deactivatesubobject') {
                 $this->subList->add($subObject, array('IsActive' => $actionName == 'activatesubobject'));
             } elseif ($actionName == 'removesubobject') {
                 $this->subList->remove($subObject);
             }
         }
     }
 }
 public function __construct($controller, $name, DataList $list)
 {
     $this->list = $list;
     $class = $list->dataClass();
     $singleton = singleton($class);
     $fields = $singleton->getFrontEndFields();
     $fields->unshift(new ListEditField("EditList", $this->list));
     $fields->push(new HiddenField("ID", "ID"));
     $actions = new FieldList(new FormAction("savenew", "Save " . $singleton->i18n_singular_name()));
     parent::__construct($controller, $name, $fields, $actions);
     $this->setupEditingMode();
     $singleton->extend('updateListEditForm', $this);
     //all fields are required
     if (!$this->validator) {
         $this->setValidator(new RequiredFields(array_keys($fields->saveableFields())));
     }
 }
Пример #27
0
 public function scaffoldFormField($title = null, $params = null)
 {
     $titleField = $this->object->hasField('Title') ? 'Title' : 'Name';
     $map = DataList::create(get_class($this->object))->map('ID', $titleField);
     $field = new DropdownField($this->name, $title, $map);
     $field->setEmptyString(' ');
     return $field;
 }
Пример #28
0
 public function removeAll()
 {
     parent::removeAll();
     $items = \DataList::create($this->dataClass);
     foreach ($items as $item) {
         $item->extend('onAfterManyManyRelationRemove');
     }
 }
Пример #29
0
 function testDataListArrayAccess()
 {
     $list = DataList::create("DataObjectTest_Team")->sort("Title");
     // We can use array access to refer to single items in the DataList, as if it were an array
     $this->assertEquals("Subteam 1", $list[0]->Title);
     $this->assertEquals("Subteam 3", $list[2]->Title);
     $this->assertEquals("Team 2", $list[4]->Title);
 }
 public function PagedDataObjectsByClassName($klazz, $pageLength = 10, $sort = 'ASC')
 {
     $req = Controller::curr()->getRequest();
     $this->lastPagedResults = new PaginatedList(DataList::create($klazz)->sort('LastEdited ' . $sort), $req);
     $this->lastPagedResults->setPageLength($pageLength);
     $this->lastPagedResults->setLimitItems($pageLength);
     return $this->lastPagedResults;
 }