/** * Prepares an element's content for being saved to the database. * * @param BaseElementModel $element * @param FieldLayoutModel $fieldLayout * @param bool $validate * @return ContentModel */ public function prepElementContentForSave(BaseElementModel $element, FieldLayoutModel $fieldLayout, $validate = true) { $elementTypeClass = $element->getElementType(); $elementType = craft()->elements->getElementType($elementTypeClass); $content = $element->getContent(); if ($validate) { // Set the required fields from the layout $requiredFields = array(); if ($elementType->hasTitles()) { $requiredFields[] = 'title'; } foreach ($fieldLayout->getFields() as $field) { if ($field->required) { $requiredFields[] = $field->fieldId; } } if ($requiredFields) { $content->setRequiredFields($requiredFields); } } // Give the fieldtypes a chance to clean up the post data foreach (craft()->fields->getAllFields() as $field) { $fieldType = craft()->fields->populateFieldType($field); if ($fieldType) { $fieldType->element = $element; $handle = $field->handle; $content->{$handle} = $fieldType->prepValueFromPost($content->{$handle}); } } return $content; }
/** * Save a Form Field * * @param SproutForms_FormModel $form * @param FieldModel $field * @param boolean $validate * @throws \Exception * @return boolean true/false */ public function saveField(SproutForms_FormModel $form, FieldModel $field, $validate = true) { if (!$validate || craft()->fields->validateField($field)) { $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null; try { if ($field->id) { $fieldLayoutFields = array(); $sortOrder = 0; // Save a new field layout with all form fields // to make sure we capture the required setting $sortOrder++; foreach ($form->getFields() as $oldField) { if ($oldField->id == $field->id) { $fieldLayoutFields[] = array('fieldId' => $field->id, 'required' => $field->required, 'sortOrder' => $sortOrder); } else { $fieldLayoutFields[] = array('fieldId' => $oldField->id, 'required' => $oldField->required, 'sortOrder' => $sortOrder); } } $fieldLayout = new FieldLayoutModel(); $fieldLayout->type = 'SproutForms_Form'; $fieldLayout->setFields($fieldLayoutFields); // Update the form model & record with our new field layout ID $form->setFieldLayout($fieldLayout); } else { // Save the new field craft()->fields->saveField($field); // Save a new field layout with all form fields $fieldLayoutFields = array(); $sortOrder = 0; foreach ($form->getFields() as $oldField) { $sortOrder++; $fieldLayoutFields[] = array('fieldId' => $oldField->id, 'required' => $oldField->required, 'sortOrder' => $sortOrder); } $sortOrder++; $fieldLayoutFields[] = array('fieldId' => $field->id, 'required' => $field->required, 'sortOrder' => $sortOrder); $fieldLayout = new FieldLayoutModel(); $fieldLayout->type = 'SproutForms_Form'; $fieldLayout->setFields($fieldLayoutFields); $form->setFieldLayout($fieldLayout); } sproutForms()->forms->saveForm($form); if ($transaction !== null) { $transaction->commit(); } } catch (\Exception $e) { if ($transaction !== null) { $transaction->rollback(); } throw $e; } return true; } else { return false; } }
/** * Any migration code in here is wrapped inside of a transaction. * * @return bool */ public function safeUp() { Craft::log('Adding a fieldLayoutId column for Asset sources.', LogLevel::Info, true); if (!craft()->db->columnExists('assetsources', 'fieldLayoutId')) { $this->addColumnAfter('assetsources', 'fieldLayoutId', array('column' => ColumnType::Int), 'id'); $this->addForeignKey('assetsources', 'fieldLayoutId', 'fieldlayouts', 'id', 'SET NULL'); $layoutId = craft()->db->createCommand()->select('id')->from('fieldlayouts')->where('type = :elementType', array(':elementType' => ElementType::Asset))->queryScalar(); if (!$layoutId) { Craft::log('No layouts found for Assets.', LogLevel::Info, true); return true; } else { $sourceIds = craft()->assetSources->getAllSourceIds(); if (empty($sourceIds)) { Craft::log("No sources exist for Assets.", LogLevel::Info, true); return true; } Craft::log('Copying the existing Assets layout to all sources.', LogLevel::Info, true); // Add the existing layout to the first source in list $sourceId = array_pop($sourceIds); craft()->db->createCommand()->update('assetsources', array('fieldLayoutId' => $layoutId), array('id' => $sourceId)); $layout = FieldLayoutModel::populateModel(FieldLayoutRecord::model()->findByPk($layoutId)); $fields = $layout->getFields(); foreach ($sourceIds as $sourceId) { $layout = new FieldLayoutRecord(); $layout->type = ElementType::Asset; $layout->save(); foreach ($fields as $field) { $fieldRecord = new FieldLayoutFieldRecord(); $fieldRecord->layoutId = $layout->id; $fieldRecord->fieldId = $field->fieldId; $fieldRecord->required = $field->required; $fieldRecord->sortOrder = $field->sortOrder; $fieldRecord->save(); } craft()->db->createCommand()->update('assetsources', array('fieldLayoutId' => $layout->id), array('id' => $sourceId)); } Craft::log('Copied the existing Assets layout to ' . (count($sourceIds) + 1) . ' sources.', LogLevel::Info, true); } } return true; }
/** * Saves a block type. * * @param MatrixBlockTypeModel $blockType The block type to be saved. * @param bool $validate Whether the block type should be validated before being saved. * Defaults to `true`. * * @throws \Exception * @return bool Whether the block type was saved successfully. */ public function saveBlockType(MatrixBlockTypeModel $blockType, $validate = true) { if (!$validate || $this->validateBlockType($blockType)) { $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null; try { $contentService = craft()->content; $fieldsService = craft()->fields; $originalFieldContext = $contentService->fieldContext; $originalFieldColumnPrefix = $contentService->fieldColumnPrefix; $originalOldFieldColumnPrefix = $fieldsService->oldFieldColumnPrefix; // Get the block type record $blockTypeRecord = $this->_getBlockTypeRecord($blockType); $isNewBlockType = $blockType->isNew(); if (!$isNewBlockType) { // Get the old block type fields $oldBlockTypeRecord = MatrixBlockTypeRecord::model()->findById($blockType->id); $oldBlockType = MatrixBlockTypeModel::populateModel($oldBlockTypeRecord); $contentService->fieldContext = 'matrixBlockType:' . $blockType->id; $contentService->fieldColumnPrefix = 'field_' . $oldBlockType->handle . '_'; $fieldsService->oldFieldColumnPrefix = 'field_' . $oldBlockType->handle . '_'; $oldFieldsById = array(); foreach ($oldBlockType->getFields() as $field) { $oldFieldsById[$field->id] = $field; } // Figure out which ones are still around foreach ($blockType->getFields() as $field) { if (!$field->isNew()) { unset($oldFieldsById[$field->id]); } } // Drop the old fields that aren't around anymore foreach ($oldFieldsById as $field) { $fieldsService->deleteField($field); } // Refresh the schema cache craft()->db->getSchema()->refresh(); } // Set the basic info on the new block type record $blockTypeRecord->fieldId = $blockType->fieldId; $blockTypeRecord->name = $blockType->name; $blockTypeRecord->handle = $blockType->handle; $blockTypeRecord->sortOrder = $blockType->sortOrder; // Save it, minus the field layout for now $blockTypeRecord->save(false); if ($isNewBlockType) { // Set the new ID on the model $blockType->id = $blockTypeRecord->id; } // Save the fields and field layout // ------------------------------------------------------------- $fieldLayoutFields = array(); $sortOrder = 0; // Resetting the fieldContext here might be redundant if this isn't a new blocktype but whatever $contentService->fieldContext = 'matrixBlockType:' . $blockType->id; $contentService->fieldColumnPrefix = 'field_' . $blockType->handle . '_'; foreach ($blockType->getFields() as $field) { // Hack to allow blank field names if (!$field->name) { $field->name = '__blank__'; } if (!$fieldsService->saveField($field, false)) { throw new Exception(Craft::t('An error occurred while saving this Matrix block type.')); } $fieldLayoutField = new FieldLayoutFieldModel(); $fieldLayoutField->fieldId = $field->id; $fieldLayoutField->required = $field->required; $fieldLayoutField->sortOrder = ++$sortOrder; $fieldLayoutFields[] = $fieldLayoutField; } $contentService->fieldContext = $originalFieldContext; $contentService->fieldColumnPrefix = $originalFieldColumnPrefix; $fieldsService->oldFieldColumnPrefix = $originalOldFieldColumnPrefix; $fieldLayoutTab = new FieldLayoutTabModel(); $fieldLayoutTab->name = 'Content'; $fieldLayoutTab->sortOrder = 1; $fieldLayoutTab->setFields($fieldLayoutFields); $fieldLayout = new FieldLayoutModel(); $fieldLayout->type = ElementType::MatrixBlock; $fieldLayout->setTabs(array($fieldLayoutTab)); $fieldLayout->setFields($fieldLayoutFields); $fieldsService->saveLayout($fieldLayout); // Update the block type model & record with our new field layout ID $blockType->setFieldLayout($fieldLayout); $blockType->fieldLayoutId = $fieldLayout->id; $blockTypeRecord->fieldLayoutId = $fieldLayout->id; // Update the block type with the field layout ID $blockTypeRecord->save(false); if (!$isNewBlockType) { // Delete the old field layout $fieldsService->deleteLayoutById($oldBlockType->fieldLayoutId); } if ($transaction !== null) { $transaction->commit(); } } catch (\Exception $e) { if ($transaction !== null) { $transaction->rollback(); } throw $e; } return true; } else { return false; } }
/** * @param FieldLayoutModel $fieldLayout * @return array */ public function getFieldLayoutDefinition(FieldLayoutModel $fieldLayout) { if ($fieldLayout->getTabs()) { $tabDefinitions = array(); foreach ($fieldLayout->getTabs() as $tab) { $tabDefinitions[$tab->name] = $this->getFieldLayoutFieldsDefinition($tab->getFields()); } return array('tabs' => $tabDefinitions); } return array('fields' => $this->getFieldLayoutFieldsDefinition($fieldLayout->getFields())); }
/** * Saves a field layout. * * @param FieldLayoutModel $layout * @param bool $saveTabs Whether to save tab records. * @return bool */ public function saveLayout(FieldLayoutModel $layout, $saveTabs = true) { // First save the layout $layoutRecord = new FieldLayoutRecord(); $layoutRecord->type = $layout->type; $layoutRecord->save(false); $layout->id = $layoutRecord->id; if ($saveTabs) { foreach ($layout->getTabs() as $tab) { $tabRecord = new FieldLayoutTabRecord(); $tabRecord->layoutId = $layout->id; $tabRecord->name = $tab->name; $tabRecord->sortOrder = $tab->sortOrder; $tabRecord->save(false); $tab->id = $tabRecord->id; foreach ($tab->getFields() as $field) { $fieldRecord = new FieldLayoutFieldRecord(); $fieldRecord->layoutId = $layout->id; $fieldRecord->tabId = $tab->id; $fieldRecord->fieldId = $field->fieldId; $fieldRecord->required = $field->required; $fieldRecord->sortOrder = $field->sortOrder; $fieldRecord->save(false); $field->id = $fieldRecord->id; } } } else { foreach ($layout->getFields() as $field) { $fieldRecord = new FieldLayoutFieldRecord(); $fieldRecord->layoutId = $layout->id; $fieldRecord->fieldId = $field->fieldId; $fieldRecord->required = $field->required; $fieldRecord->sortOrder = $field->sortOrder; $fieldRecord->save(false); $field->id = $fieldRecord->id; } } return true; }
private function _exportFieldLayout(FieldLayoutModel $fieldLayout) { if ($fieldLayout->getTabs()) { $tabDefs = array(); foreach ($fieldLayout->getTabs() as $tab) { $tabDefs[$tab->name] = array(); foreach ($tab->getFields() as $field) { $tabDefs[$tab->name][$field->getField()->handle] = $field->required; } } return array('tabs' => $tabDefs); } else { $fieldDefs = array(); foreach ($fieldLayout->getFields() as $field) { $fieldDefs[$field->getField()->handle] = $field->required; } return array('fields' => $fieldDefs); } }
/** * Saves a field layout. * * @param FieldLayoutModel $layout * * @return bool */ public function saveLayout(FieldLayoutModel $layout) { // First save the layout $layoutRecord = new FieldLayoutRecord(); $layoutRecord->type = $layout->type; $layoutRecord->save(false); $layout->id = $layoutRecord->id; foreach ($layout->getTabs() as $tab) { $tabRecord = new FieldLayoutTabRecord(); $tabRecord->layoutId = $layout->id; $tabRecord->name = $tab->name; $tabRecord->sortOrder = $tab->sortOrder; $tabRecord->save(false); $tab->id = $tabRecord->id; foreach ($tab->getFields() as $field) { $fieldRecord = new FieldLayoutFieldRecord(); $fieldRecord->layoutId = $layout->id; $fieldRecord->tabId = $tab->id; $fieldRecord->fieldId = $field->fieldId; $fieldRecord->required = $field->required; $fieldRecord->sortOrder = $field->sortOrder; $fieldRecord->save(false); $field->id = $fieldRecord->id; } } // Fire an 'onSaveFieldLayout' event $this->onSaveFieldLayout(new Event($this, array('layout' => $layout))); return true; }
/** * Creates initial database content for the install. * * @access private * @param $inputs * @return null */ private function _createDefaultContent($inputs) { // Default tag set Craft::log('Creating the Default tag set.'); $tagSet = new TagSetModel(); $tagSet->name = Craft::t('Default'); $tagSet->handle = 'default'; // Save it if (craft()->tags->saveTagSet($tagSet)) { Craft::log('Default tag set created successfully.'); } else { Craft::log('Could not save the Default tag set.', LogLevel::Warning); } // Default field group Craft::log('Creating the Default field group.'); $group = new FieldGroupModel(); $group->name = Craft::t('Default'); if (craft()->fields->saveGroup($group)) { Craft::log('Default field group created successfully.'); } else { Craft::log('Could not save the Default field group.', LogLevel::Warning); } // Heading field Craft::log('Creating the Heading field.'); $headingField = new FieldModel(); $headingField->groupId = $group->id; $headingField->name = Craft::t('Heading'); $headingField->handle = 'heading'; $headingField->translatable = true; $headingField->type = 'PlainText'; if (craft()->fields->saveField($headingField)) { Craft::log('Heading field created successfully.'); } else { Craft::log('Could not save the Heading field.', LogLevel::Warning); } // Body field Craft::log('Creating the Body field.'); $bodyField = new FieldModel(); $bodyField->groupId = $group->id; $bodyField->name = Craft::t('Body'); $bodyField->handle = 'body'; $bodyField->translatable = true; $bodyField->type = 'RichText'; $bodyField->settings = array('configFile' => 'Standard.json'); if (craft()->fields->saveField($bodyField)) { Craft::log('Body field created successfully.'); } else { Craft::log('Could not save the Body field.', LogLevel::Warning); } // Tags field Craft::log('Creating the Tags field.'); $tagsField = new FieldModel(); $tagsField->groupId = $group->id; $tagsField->name = Craft::t('Tags'); $tagsField->handle = 'tags'; $tagsField->type = 'Tags'; $tagsField->settings = array('source' => 'tagset:' . $tagSet->id); if (craft()->fields->saveField($tagsField)) { Craft::log('Tags field created successfully.'); } else { Craft::log('Could not save the Tags field.', LogLevel::Warning); } // Homepage global set Craft::log('Creating the Homepage global set.'); $homepageLayoutFields = array(array('fieldId' => $headingField->id, 'sortOrder' => 1), array('fieldId' => $bodyField->id, 'sortOrder' => 2)); $homepageLayout = new FieldLayoutModel(); $homepageLayout->type = ElementType::GlobalSet; $homepageLayout->setFields($homepageLayoutFields); $homepageGlobalSet = new GlobalSetModel(); $homepageGlobalSet->name = Craft::t('Homepage'); $homepageGlobalSet->handle = 'homepage'; $homepageGlobalSet->setFieldLayout($homepageLayout); if (craft()->globals->saveSet($homepageGlobalSet)) { Craft::log('Homepage global set created successfully.'); } else { Craft::log('Could not save the Homepage global set.', LogLevel::Warning); } // Homepage content $vars = array('siteName' => ucfirst(craft()->request->getServerName())); Craft::log('Setting the Homepage content.'); $homepageGlobalSet->locale = $inputs['locale']; $homepageGlobalSet->getContent()->setAttributes(array('heading' => Craft::t('Welcome to {siteName}!', $vars), 'body' => '<p>' . Craft::t('It’s true, this site doesn’t have a whole lot of content yet, but don’t worry. Our web developers have just installed the CMS, and they’re setting things up for the content editors this very moment. Soon {siteName} will be an oasis of fresh perspectives, sharp analyses, and astute opinions that will keep you coming back again and again.', $vars) . '</p>')); if (craft()->globals->saveContent($homepageGlobalSet)) { Craft::log('Homepage content set successfully.'); } else { Craft::log('Could not set the Homepage content.', LogLevel::Warning); } // News section Craft::log('Creating the News section.'); $newsLayoutFields = array(array('fieldId' => $bodyField->id, 'required' => true, 'sortOrder' => 1), array('fieldId' => $tagsField->id, 'sortOrder' => 2)); $newsLayoutTabs = array(array('name' => Craft::t('Content'), 'sortOrder' => 1, 'fields' => $newsLayoutFields)); $newsLayout = new FieldLayoutModel(); $newsLayout->type = ElementType::Entry; $newsLayout->setTabs($newsLayoutTabs); $newsLayout->setFields($newsLayoutFields); $newsSection = new SectionModel(); $newsSection->name = Craft::t('News'); $newsSection->handle = 'news'; $newsSection->hasUrls = true; $newsSection->template = 'news/_entry'; $newsSection->setLocales(array($inputs['locale'] => SectionLocaleModel::populateModel(array('locale' => $inputs['locale'], 'urlFormat' => 'news/{postDate.year}/{slug}')))); $newsSection->setFieldLayout($newsLayout); if (craft()->sections->saveSection($newsSection)) { Craft::log('News section created successfully.'); } else { Craft::log('Could not save the News section.', LogLevel::Warning); } // News entry Craft::log('Creating a News entry.'); $newsEntry = new EntryModel(); $newsEntry->sectionId = $newsSection->id; $newsEntry->locale = $inputs['locale']; $newsEntry->authorId = $this->_user->id; $newsEntry->enabled = true; $newsEntry->getContent()->title = Craft::t('We just installed Craft!'); $newsEntry->getContent()->setAttributes(array('body' => '<p>' . Craft::t('Craft is the CMS that’s powering {siteName}. It’s beautiful, powerful, flexible, and easy-to-use, and it’s made by Pixel & Tonic. We can’t wait to dive in and see what it’s capable of!', $vars) . '</p><!--pagebreak--><p>' . Craft::t('This is even more captivating content, which you couldn’t see on the News index page because it was entered after a Page Break, and the News index template only likes to show the content on the first page.') . '</p><p>' . Craft::t('Craft: a nice alternative to Word, if you’re making a website.') . '</p>')); if (craft()->entries->saveEntry($newsEntry)) { Craft::log('News entry created successfully.'); } else { Craft::log('Could not save the News entry.', LogLevel::Warning); } }
/** * Updates the search indexes based on the new content values. * * @param BaseElementModel $element * @param ContentModel $content * @param FieldLayoutModel $fieldLayout * @param array|null &$nonTranslatableFields * @param array|null &$otherContentModels * * @return null */ private function _updateSearchIndexes(BaseElementModel $element, ContentModel $content, FieldLayoutModel $fieldLayout, &$nonTranslatableFields = null, &$otherContentModels = null) { $searchKeywordsByLocale = array(); foreach ($fieldLayout->getFields() as $fieldLayoutField) { $field = $fieldLayoutField->getField(); if ($field) { $fieldType = $field->getFieldType(); if ($fieldType) { $fieldType->element = $element; $handle = $field->handle; // Set the keywords for the content's locale $fieldSearchKeywords = $fieldType->getSearchKeywords($element->getFieldValue($handle)); $searchKeywordsByLocale[$content->locale][$field->id] = $fieldSearchKeywords; // Should we queue up the other locales' new keywords too? if (isset($nonTranslatableFields[$field->id])) { foreach ($otherContentModels as $otherContentModel) { $searchKeywordsByLocale[$otherContentModel->locale][$field->id] = $fieldSearchKeywords; } } } } } foreach ($searchKeywordsByLocale as $localeId => $keywords) { craft()->search->indexElementFields($element->id, $localeId, $keywords); } }
public function getFieldLayout(Formerly_FormModel $form) { if (!$form || !$form->id) { return false; } $questions = $this->getQuestionsByFormId($form->id); $fields = array(); foreach ($questions as $question) { $field = new FieldLayoutFieldModel(); $field->fieldId = $question->fieldId; $field->required = $question->required; $field->sortOrder = $question->sortOrder; $fields[] = $field; } $layout = new FieldLayoutModel(); $layout->type = 'Form'; $layout->setFields($fields); return $layout; }
/** * Attempt to import a field layout. * * @param array $fieldLayoutDef * * @return FieldLayoutModel */ private function _importFieldLayout(array $fieldLayoutDef) { $layoutTabs = array(); $layoutFields = array(); if (array_key_exists('tabs', $fieldLayoutDef)) { $tabSortOrder = 0; foreach ($fieldLayoutDef['tabs'] as $tabName => $tabDef) { $layoutTabFields = array(); foreach ($tabDef as $fieldHandle => $required) { $fieldSortOrder = 0; $field = craft()->fields->getFieldByHandle($fieldHandle); if ($field) { $layoutField = new FieldLayoutFieldModel(); $layoutField->setAttributes(array('fieldId' => $field->id, 'required' => $required, 'sortOrder' => ++$fieldSortOrder)); $layoutTabFields[] = $layoutField; $layoutFields[] = $layoutField; } } $layoutTab = new FieldLayoutTabModel(); $layoutTab->setAttributes(array('name' => $tabName, 'sortOrder' => ++$tabSortOrder)); $layoutTab->setFields($layoutTabFields); $layoutTabs[] = $layoutTab; } } else { if (array_key_exists('fields', $fieldLayoutDef)) { $fieldSortOrder = 0; foreach ($fieldLayoutDef['fields'] as $fieldHandle => $required) { $field = craft()->fields->getFieldByHandle($fieldHandle); if ($field) { $layoutField = new FieldLayoutFieldModel(); $layoutField->setAttributes(array('fieldId' => $field->id, 'required' => $required, 'sortOrder' => ++$fieldSortOrder)); $layoutFields[] = $layoutField; } } } } $fieldLayout = new FieldLayoutModel(); $fieldLayout->type = ElementType::Entry; $fieldLayout->setTabs($layoutTabs); $fieldLayout->setFields($layoutFields); return $fieldLayout; }
public function getCustomFieldsFromFieldLayout(FieldLayoutModel $fieldLayout) { $fields = array(); $fieldLayoutFieldModels = $fieldLayout->getFields(); foreach ($fieldLayoutFieldModels as $fieldLayoutFieldModel) { if (!in_array($fieldLayoutFieldModel->field->getFieldType()->name, $this->getUnsupportedFieldTypes())) { $fields[$fieldLayoutFieldModel->field->handle] = $fieldLayoutFieldModel->field; } } return $fields; }