Create a new pivot attachment record.

@param  int   $id
@param  bool  $timed
@return array
492018
protected function baseAttachRecord($id, $timed)
    {
        return Arr::add(
            parent::baseAttachRecord($id, $timed), $this->morphType, $this->morphClass
        );
    }
1137726
public function getAggregateHistoryFor(Identity $id, $offset = 0, $max = null)
    {
        return new CommittedEvents(
            $id,
            array_filter(
                array_slice($this->events[(string)$id], $offset, $max, true),
                function (DomainEvent $event) use ($id) {
                    return $event->getAggregateIdentity()->equals($id);
                }
            )
        );
    }
667559
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;
	}
949731
protected function export_tour($id) {
        $tour = tour::instance($id);

        // Grab the full data record.
        $export = $tour->to_record();

        // Remove the id.
        unset($export->id);

        // Set the version.
        $export->version = get_config('tool_usertours', 'version');

        // Step export.
        $export->steps = [];
        foreach ($tour->get_steps() as $step) {
            $record = $step->to_record();
            unset($record->id);
            unset($record->tourid);

            $export->steps[] = $record;
        }

        $exportstring = json_encode($export);

        $filename = 'tour_export_' . $tour->get_id() . '_' . time() . '.json';

        // Force download.
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
        header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
        header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . 'GMT');
        header('Pragma: no-cache');
        header('Accept-Ranges: none');
        header('Content-disposition: attachment; filename=' . $filename);
        header('Content-length: ' . strlen($exportstring));
        header('Content-type: text/calendar; charset=utf-8');

        echo $exportstring;
        die;
    }
1293322
public function attach($id)
    {
        if ($this->mapper === null) {
            throw new InvalidStateException('Missing mapper in ' . get_called_class() . '.');
        }
        $this->row->attach($id, $this->mapper->getTable(get_called_class()));
    }
1238129
protected function formatAttachRecords($ids, array $attributes)
    {
        $records = [];

        $hasTimestamps = ($this->hasPivotColumn($this->createdAt()) ||
                  $this->hasPivotColumn($this->updatedAt()));

        // To create the attachment records, we will simply spin through the IDs given
        // and create a new record to insert for each ID. Each ID may actually be a
        // key in the array, with extra attributes to be placed in other columns.
        foreach ($ids as $key => $value) {
            $records[] = $this->formatAttachRecord(
                $key, $value, $attributes, $hasTimestamps
            );
        }

        return $records;
    }
729360
public function getCampaignEditForm($id)
    {
        // Get record-specific fields
        $record = ChangeSet::get()->byID($id);
        if (!$record) {
            $this->httpError(404);
            return null;
        }
        if (!$record->canView()) {
            $this->httpError(403);
            return null;
        }

        $fields = $record->getCMSFields();

        // Add standard fields
        $fields->push(HiddenField::create('ID'));
        $form = Form::create(
            $this,
            'campaignEditForm',
            $fields,
            FieldList::create(
                FormAction::create('save', _t(__CLASS__.'SAVE', 'Save'))
                    ->setIcon('save')
                    ->setSchemaState([
                        'data' => [
                            'pristineTitle' => _t(__CLASS__.'SAVED', 'Saved'),
                            'pristineIcon' => 'tick',
                            'dirtyTitle' => _t(__CLASS__.'SAVE', 'Save'),
                            'dirtyIcon' => 'save',
                            'pristineClass' => 'btn-outline-primary',
                            'dirtyClass' => '',
                        ],
                    ]),
                FormAction::create('cancel', _t(__CLASS__.'.CANCEL', 'Cancel'))
                    ->setUseButtonTag(true)
            ),
            new RequiredFields('Name')
        );

        // Load into form
        $form->loadDataFrom($record);

        // Set form action handler with ID included
        $form->setRequestHandler(
            LeftAndMainFormRequestHandler::create($form, [ $id ])
        );

        // Configure form to respond to validation errors with form schema
        // if requested via react.
        $form->setValidationResponseCallback(function (ValidationResult $errors) use ($form, $id, $record) {
            $schemaId = Controller::join_links(
                $this->Link('schema'),
                'campaignEditForm',
                $id
            );
            return $this->getSchemaResponse($schemaId, $form, $errors);
        });

        $form->setNotifyUnsavedChanges(true);

        return $form;
    }
486551
private function createDeleteForm($id) {
        return $this->createFormBuilder()
                        ->setAction($this->generateUrl('admin_news_category_delete', array('id' => $id)))
                        ->setMethod('DELETE')
                        ->add('submit', 'submit', array('label' => 'Delete',
                            'attr' => array(
                                    'onclick' => 'return confirm("Estás seguro?")'
                            )))
                        ->getForm()
        ;
    }
1062333
public function mediaSendToEditor($html, $id, $attachment) {
		if(!$this->renderPDF) {
			return $html;
		}

		$mime = get_post_mime_type($id);
		if($mime == 'application/pdf') {
			$align = isset($attachment['align']) ? $attachment['align'] : 'none';
			$size = isset($attachment['image-size']) ? $attachment['image-size'] : 'medium';
			$alt = isset($attachment['image_alt']) ? $attachment['image_alt'] : '';

			// No whitespace-only captions.
			$caption = isset($attachment['post_excerpt']) ? $attachment['post_excerpt'] : '';
			if('' === trim($caption)) {
				$caption = '';
			}

			$url = empty($attachment['url']) ? '' : $attachment['url'];
			$rel = (strpos($url, 'attachment_id') || get_attachment_link($id) == $url);

			$title = ''; // We no longer insert title tags into <img> tags, as they are redundant.
			$html = get_image_send_to_editor($id, $caption, $title, $align, $url, $rel, $size, $alt);

		}

		return $html;
	}
1264468
public function attachFiles($id, $table, $files)
    {
        foreach ($files as $file) {
            if (!empty($file)) {
                $this->attachFile($id, $table, $file);
            }
        }
    }
961501
public function attach($id, array $attributes = [], $touch = true)
    {
        // Here we will insert the attachment records into the pivot table. Once we have
        // inserted the records, we will touch the relationships if necessary and the
        // function will return. We can parse the IDs before inserting the records.
        $this->newPivotStatement()->insert($this->formatAttachRecords(
            $this->parseIds($id), $attributes
        ));

        if ($touch) {
            $this->touchIfTouching();
        }
    }
1145658
public function retrieveWithScheduledChanges(string $id, array $headers = [])
    {
        $url = $this->url('subscriptions/%s/retrieve_with_scheduled_changes', $id);

        return $this->get($url, [], $headers);
    }
1042868
public function attachTag($id)
    {
        if ( ! $this->tags->contains($id))
        {
            return $this->tags()->attach($id);
        }
    }
773954
protected function addTimestampsToAttachment(array $record, $exists = false)
    {
        $fresh = $this->parent->freshTimestamp();

        if ($this->using) {
            $pivotModel = new $this->using;

            $fresh = $fresh->format($pivotModel->getDateFormat());
        }

        if (! $exists && $this->hasPivotColumn($this->createdAt())) {
            $record[$this->createdAt()] = $fresh;
        }

        if ($this->hasPivotColumn($this->updatedAt())) {
            $record[$this->updatedAt()] = $fresh;
        }

        return $record;
    }
870186
public function createEditForm($id) {
        $entity = $this->read_handler->get($id);
        return $form = $this->doCreate($this->getDefaultTypeClass(), $entity);
    }
952121
public function setAttachmentId($id)
    {
        $this->payload['attachment_id'] = $id;
        unset($this->payload['url'], $this->payload['is_reusable']);

        return $this;
    }
33513
public function destroyRecord($id)
    {
        $deleteWentOk = $this->getDestroy($id);

        if ($deleteWentOk) {

            // Get the field list
            // The field list resides in the model. Exists either as a property, or returned from method -- but not both.
            if ($this->model->field_list) {
                // exists as a property
                $fieldList = $this->model->field_list;
            } else {
                // exists via method
                $fieldList = $this->model->getFieldList();
            }

            // What would the pivot table's fieldname be, for the pivot table's field referring to $id?
            $pivotTableFieldName = strtolower($this->model->model_class) . "_id";

            // Iterate through the field list, looking for pivot tables
            // Iterate through the field list to identify possible table relationships that use pivot database tables
            foreach ($fieldList as $field) {

                if ($field['type'] == "related_table")  {

                    if (($field['related_pivot_table'])) {
                        // Delete associated records
                        DB::table($field['related_pivot_table_name'])
                            ->where($pivotTableFieldName, '=', $id)
                            ->delete();
                    }

                }
            }

            return true;
        }

        return false;
    }