当前位置: 首页>>代码示例>>PHP>>正文


PHP Craft类代码示例

本文整理汇总了PHP中Craft的典型用法代码示例。如果您正苦于以下问题:PHP Craft类的具体用法?PHP Craft怎么用?PHP Craft使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Craft类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: sendMessage

 /**
  * Sends an email submitted through a contact form.
  *
  * @param ContactFormModel $message
  * @throws Exception
  * @return bool
  */
 public function sendMessage(ContactFormModel $message)
 {
     $settings = craft()->plugins->getPlugin('contactform')->getSettings();
     if (!$settings->toEmail) {
         throw new Exception('The "To Email" address is not set on the plugin’s settings page.');
     }
     // Fire an 'onBeforeSend' event
     Craft::import('plugins.contactform.events.ContactFormEvent');
     $event = new ContactFormEvent($this, array('message' => $message));
     $this->onBeforeSend($event);
     if ($event->isValid) {
         if (!$event->fakeIt) {
             $toEmails = ArrayHelper::stringToArray($settings->toEmail);
             foreach ($toEmails as $toEmail) {
                 $email = new EmailModel();
                 $emailSettings = craft()->email->getSettings();
                 $email->fromEmail = $emailSettings['emailAddress'];
                 $email->replyTo = $message->fromEmail;
                 $email->sender = $emailSettings['emailAddress'];
                 $email->fromName = $settings->prependSender . ($settings->prependSender && $message->fromName ? ' ' : '') . $message->fromName;
                 $email->toEmail = $toEmail;
                 $email->subject = $settings->prependSubject . ($settings->prependSubject && $message->subject ? ' - ' : '') . $message->subject;
                 $email->body = $message->message;
                 if ($message->attachment) {
                     $email->addAttachment($message->attachment->getTempName(), $message->attachment->getName(), 'base64', $message->attachment->getType());
                 }
                 craft()->email->sendEmail($email);
             }
         }
         return true;
     }
     return false;
 }
开发者ID:besimhu,项目名称:CraftCMS-Boilerplate,代码行数:40,代码来源:ContactFormService.php

示例2: getInputHtml

 public function getInputHtml($name, $value)
 {
     // Get site templates path
     $templatesPath = $siteTemplatesPath = craft()->path->getSiteTemplatesPath();
     // Check if the templates path is overriden by configuration
     // TODO: Normalize path
     $limitToSubfolder = craft()->config->get('templateselectSubfolder');
     if ($limitToSubfolder) {
         $templatesPath = $templatesPath . rtrim($limitToSubfolder, '/') . '/';
     }
     // Check if folder exists, or give error
     if (!IOHelper::folderExists($templatesPath)) {
         throw new \InvalidArgumentException('(Template Select) Folder doesn\'t exist: ' . $templatesPath);
     }
     // Get folder contents
     $templates = IOHelper::getFolderContents($templatesPath, TRUE);
     // Add placeholder for when there is no template selected
     $filteredTemplates = array('' => Craft::t('No template selected'));
     // Turn array into ArrayObject
     $templates = new \ArrayObject($templates);
     // Iterate over template list
     // * Remove full path
     // * Remove folders from list
     for ($list = $templates->getIterator(); $list->valid(); $list->next()) {
         $filename = $list->current();
         $filename = str_replace($templatesPath, '', $filename);
         $filenameIncludingSubfolder = $limitToSubfolder ? $limitToSubfolder . $filename : $filename;
         $isTemplate = preg_match("/(.html|.twig)\$/u", $filename);
         if ($isTemplate) {
             $filteredTemplates[$filenameIncludingSubfolder] = $filename;
         }
     }
     // Render field
     return craft()->templates->render('_includes/forms/select', array('name' => $name, 'value' => $value, 'options' => $filteredTemplates));
 }
开发者ID:alexrubin,项目名称:Craft-TemplateSelect,代码行数:35,代码来源:TemplateSelect_SelectFieldType.php

示例3: safeUp

 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     // Create the categorygroups table
     if (!craft()->db->tableExists('categorygroups')) {
         Craft::log('Creating the categorygroups table', LogLevel::Info, true);
         $this->createTable('categorygroups', array('structureId' => array('column' => ColumnType::Int, 'null' => false), 'fieldLayoutId' => array('column' => ColumnType::Int), 'name' => array('column' => ColumnType::Varchar, 'required' => true), 'handle' => array('column' => ColumnType::Varchar, 'required' => true), 'hasUrls' => array('column' => ColumnType::Bool, 'required' => true, 'default' => true), 'template' => array('column' => ColumnType::Varchar, 'maxLength' => 500)));
         $this->createIndex('categorygroups', 'name', true);
         $this->createIndex('categorygroups', 'handle', true);
         $this->addForeignKey('categorygroups', 'structureId', 'structures', 'id', 'CASCADE');
         $this->addForeignKey('categorygroups', 'fieldLayoutId', 'fieldlayouts', 'id', 'SET NULL');
     }
     // Create the categorygroups_i18n table
     if (!craft()->db->tableExists('categorygroups_i18n')) {
         Craft::log('Creating the categorygroups_i18n table', LogLevel::Info, true);
         $this->createTable('categorygroups_i18n', array('groupId' => array('column' => ColumnType::Int, 'required' => true), 'locale' => array('column' => ColumnType::Locale, 'required' => true), 'urlFormat' => array('column' => ColumnType::Varchar), 'nestedUrlFormat' => array('column' => ColumnType::Varchar)));
         $this->createIndex('categorygroups_i18n', 'groupId,locale', true);
         $this->addForeignKey('categorygroups_i18n', 'groupId', 'categorygroups', 'id', 'CASCADE');
         $this->addForeignKey('categorygroups_i18n', 'locale', 'locales', 'locale', 'CASCADE', 'CASCADE');
     }
     // Create the categories table
     if (!craft()->db->tableExists('categories')) {
         Craft::log('Creating the categories table', LogLevel::Info, true);
         $this->createTable('categories', array('id' => array('column' => ColumnType::Int, 'required' => true, 'primaryKey' => true), 'groupId' => array('column' => ColumnType::Int, 'required' => true)), null, false);
         $this->addForeignKey('categories', 'id', 'elements', 'id', 'CASCADE');
         $this->addForeignKey('categories', 'groupId', 'categorygroups', 'id', 'CASCADE');
     }
     return true;
 }
开发者ID:scisahaha,项目名称:generator-craft,代码行数:33,代码来源:m140401_000011_categories.php

示例4: actionSaveDefault

 public function actionSaveDefault()
 {
     $this->requirePostRequest();
     // check if this is a new or existing default
     if (craft()->request->getPost('sproutseo_fields[id]') == null) {
         $id = false;
     } else {
         $id = craft()->request->getPost('sproutseo_fields[id]');
     }
     $model = new SproutSeo_MetaModel();
     $model->id = $id;
     $defaultFields = craft()->request->getPost('sproutseo_fields');
     // Convert Checkbox Array into comma-delimited String
     if (isset($defaultFields['robots'])) {
         $defaultFields['robots'] = SproutSeoMetaHelper::prepRobotsAsString($defaultFields['robots']);
     }
     // Make our images single IDs instead of an array
     $defaultFields['ogImage'] = !empty($defaultFields['ogImage']) ? $defaultFields['ogImage'][0] : null;
     $defaultFields['twitterImage'] = !empty($defaultFields['twitterImage']) ? $defaultFields['twitterImage'][0] : null;
     $model->setAttributes($defaultFields);
     if (sproutSeo()->defaults->saveDefault($model)) {
         craft()->userSession->setNotice(Craft::t('New default saved.'));
         $this->redirectToPostedUrl();
     } else {
         craft()->userSession->setError(Craft::t("Couldn't save the default."));
         // Send the field back to the template
         craft()->urlManager->setRouteVariables(array('default' => $model));
     }
 }
开发者ID:aladrach,项目名称:Bluefoot-Craft-Starter,代码行数:29,代码来源:SproutSeo_DefaultsController.php

示例5: actionReset

 /**
  * Reset count
  */
 public function actionReset()
 {
     $entryId = craft()->request->getRequiredParam('entryId');
     craft()->entryCount->reset($entryId);
     craft()->userSession->setNotice(Craft::t('Entry count reset.'));
     $this->redirect('entrycount');
 }
开发者ID:jackmcgreevy,项目名称:jackmcgreevy.com,代码行数:10,代码来源:EntryCountController.php

示例6: safeUp

 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     if (!craft()->db->columnExists('elements_i18n', 'slug')) {
         Craft::log('Creating an elements_i18n.slug column.', LogLevel::Info, true);
         $this->addColumnAfter('elements_i18n', 'slug', ColumnType::Varchar, 'locale');
     }
     if (craft()->db->tableExists('entries_i18n')) {
         Craft::log('Copying the slugs from entries_i18n into elements_i18n.', LogLevel::Info, true);
         $rows = craft()->db->createCommand()->select('entryId, locale, slug')->from('entries_i18n')->queryAll();
         foreach ($rows as $row) {
             $this->update('elements_i18n', array('slug' => $row['slug']), array('elementId' => $row['entryId'], 'locale' => $row['locale']));
         }
         Craft::log('Dropping the entries_i18n table.');
         $this->dropTable('entries_i18n');
     }
     if (!craft()->db->columnExists('elements_i18n', 'enabled')) {
         Craft::log('Creating an elements_i18n.enabled column.', LogLevel::Info, true);
         $this->addColumnAfter('elements_i18n', 'enabled', array('column' => ColumnType::Bool, 'default' => true), 'uri');
     }
     MigrationHelper::refresh();
     MigrationHelper::dropIndexIfExists('elements_i18n', array('slug', 'locale'));
     MigrationHelper::dropIndexIfExists('elements_i18n', array('enabled'));
     $this->createIndex('elements_i18n', 'slug,locale');
     $this->createIndex('elements_i18n', 'enabled');
     return true;
 }
开发者ID:kentonquatman,项目名称:portfolio,代码行数:31,代码来源:m140401_000002_elements_i18n_tweaks.php

示例7: _loadCodeMirror

    private function _loadCodeMirror()
    {
        if ($this->_actualSettingsPage()) {
            craft()->templates->includeCssResource('cpcss/css/codemirror.css');
            craft()->templates->includeCssResource('cpcss/css/blackboard.css');
            craft()->templates->includeJsResource('cpcss/js/codemirror-css.js');
            craft()->templates->includeJs('
$(function () {
    var $redirect = $("' . addslashes('input[type="hidden"][name="redirect"][value$="settings/plugins"]') . '"),
        $saveBtn = $("' . addslashes('input[type="submit"') . '").wrap("' . addslashes('<div class="btngroup" />') . '"),
        $menuBtn = $("' . addslashes('<div class="btn submit menubtn" />') . '").appendTo($saveBtn.parent()),
        $menu = $("' . addslashes('<div class="menu" />') . '").appendTo($saveBtn.parent()),
        $items = $("<ul />").appendTo($menu),
        $continueOpt = $("' . addslashes('<li><a class="formsubmit" data-redirect="' . UrlHelper::getCpUrl('settings/plugins/cpcss') . '">' . Craft::t('Save and continue editing') . '<span class="shortcut">' . (craft()->request->getClientOs() === 'Mac' ? '⌘' : 'Ctrl+') . 'S</span></a></li>') . '").appendTo($items);
    new Garnish.MenuBtn($menuBtn, {
        onOptionSelect : function (option) {
            Craft.cp.submitPrimaryForm();
        }
    });
    $saveBtn.on("click", function (e) { $redirect.attr("value", "' . UrlHelper::getCpUrl('settings/plugins') . '"); });
    $redirect.attr("value", "' . UrlHelper::getCpUrl('settings/plugins/cpcss') . '");
    CodeMirror.fromTextArea(document.getElementById("settings-additionalCss"), {
        indentUnit: 4,
        styleActiveLine: true,
        lineNumbers: true,
        lineWrapping: true,
        theme: "blackboard"
    });
});', true);
        }
    }
开发者ID:jimmylorunning,项目名称:acf,代码行数:31,代码来源:CpCssPlugin.php

示例8: defineAttributes

 /**
  * @access protected
  * @return array
  */
 protected function defineAttributes()
 {
     $requiredTitle = isset($this->_requiredFields) && in_array('title', $this->_requiredFields);
     $attributes = array('id' => AttributeType::Number, 'elementId' => AttributeType::Number, 'locale' => AttributeType::Locale, 'title' => array(AttributeType::String, 'required' => $requiredTitle));
     if (Craft::isInstalled() && !craft()->isConsole()) {
         $allFields = craft()->fields->getAllFields();
         foreach ($allFields as $field) {
             $fieldType = craft()->fields->populateFieldType($field);
             if ($fieldType) {
                 $attributeConfig = $fieldType->defineContentAttribute();
             }
             // Default to Mixed
             if (!$fieldType || !$attributeConfig) {
                 $attributeConfig = AttributeType::Mixed;
             }
             $attributeConfig = ModelHelper::normalizeAttributeConfig($attributeConfig);
             $attributeConfig['label'] = $field->name;
             if (isset($this->_requiredFields) && in_array($field->id, $this->_requiredFields)) {
                 $attributeConfig['required'] = true;
             }
             $attributes[$field->handle] = $attributeConfig;
         }
     }
     return $attributes;
 }
开发者ID:kentonquatman,项目名称:portfolio,代码行数:29,代码来源:ContentModel.php

示例9: save

 /**
  * @param Market_TaxCategoryModel $model
  *
  * @return bool
  * @throws Exception
  * @throws \CDbException
  * @throws \Exception
  */
 public function save(Market_TaxCategoryModel $model)
 {
     if ($model->id) {
         $record = Market_TaxCategoryRecord::model()->findById($model->id);
         if (!$record) {
             throw new Exception(Craft::t('No tax category exists with the ID “{id}”', ['id' => $model->id]));
         }
     } else {
         $record = new Market_TaxCategoryRecord();
     }
     $record->name = $model->name;
     $record->code = $model->code;
     $record->description = $model->description;
     $record->default = $model->default;
     $record->validate();
     $model->addErrors($record->getErrors());
     if (!$model->hasErrors()) {
         // Save it!
         $record->save(false);
         // Now that we have a record ID, save it on the model
         $model->id = $record->id;
         //If this was the default make all others not the default.
         if ($model->default) {
             Market_TaxCategoryRecord::model()->updateAll(['default' => 0], 'id != ?', [$record->id]);
         }
         return true;
     } else {
         return false;
     }
 }
开发者ID:aladrach,项目名称:Bluefoot-Craft-Starter,代码行数:38,代码来源:Market_TaxCategoryService.php

示例10: actionNew

 public function actionNew()
 {
     $this->requirePostRequest();
     $settings = craft()->request->getRequiredPost('settings');
     $layoutId = $settings['layoutId'];
     $label = $settings['label'];
     $handle = $settings['handle'];
     $url = $settings['url'];
     $newWindow = (bool) $settings['newWindow'];
     $variables = array('layoutId' => $layoutId, 'handle' => $handle, 'label' => $label, 'url' => $url, 'manual' => true, 'newWindow' => $newWindow);
     if ($label && $url) {
         $result = craft()->cpNav_nav->createNav($variables);
         if ($result['success']) {
             craft()->userSession->setNotice(Craft::t('Menu item added.'));
         } else {
             craft()->userSession->setError(Craft::t('Could not create menu item.'));
         }
     } else {
         craft()->userSession->setError(Craft::t('Label and URL are required.'));
     }
     if (craft()->request->isAjaxRequest()) {
         $this->returnJson(array('success' => true, 'nav' => $result['nav']));
     } else {
         $this->redirectToPostedUrl();
     }
 }
开发者ID:aladrach,项目名称:Bluefoot-Craft-Starter,代码行数:26,代码来源:CpNavController.php

示例11: safeUp

 /**
  * Any migration code in here is wrapped inside of a transaction.
  *
  * @return bool
  */
 public function safeUp()
 {
     Craft::log('Dropping the movePermission column from the structures table...', LogLevel::Info, true);
     $this->dropColumn('structures', 'movePermission');
     Craft::log('Done dropping the movePermission column from the structures table.', LogLevel::Info, true);
     return true;
 }
开发者ID:jmstan,项目名称:craft-website,代码行数:12,代码来源:m141030_000001_drop_structure_move_permission.php

示例12: _getInputHtml

 private function _getInputHtml($name, $value, $static)
 {
     $columns = $this->getSettings()->columns;
     $tableData = $this->getSettings()->tableData;
     if ($columns) {
         // Translate the column headings
         foreach ($columns as &$column) {
             if (!empty($column['heading'])) {
                 $column['heading'] = Craft::t($column['heading']);
             }
         }
         // Minor fix for Backwards-compatibility - migrate old data into new key
         foreach ($value as $key => $val) {
             if (is_numeric($key)) {
                 $value['row' . ($key + 1)] = $val;
                 unset($value[$key]);
             }
         }
         if (!$value) {
             if (is_array($tableData)) {
                 $value = $tableData;
             }
         } else {
             // Merge the saved existing values and any new rows
             foreach ($tableData as $key => $val) {
                 if (!isset($value[$key])) {
                     $value[$key] = $val;
                 }
             }
         }
         $id = craft()->templates->formatInputId($name);
         return craft()->templates->render('settable/field', array('id' => $id, 'name' => $name, 'cols' => $columns, 'rows' => $value));
     }
 }
开发者ID:nervetattoo,项目名称:SetTable,代码行数:34,代码来源:SetTableFieldType.php

示例13: actionTriggerCommand

 /**
  * Trigger a command.
  */
 public function actionTriggerCommand()
 {
     $this->requirePostRequest();
     $this->requireAjaxRequest();
     // Get POST data and trigger the command
     $command = craft()->request->getPost('command', false);
     $service = craft()->request->getPost('service', false);
     $vars = craft()->request->getPost('vars', false);
     $result = craft()->amCommand->triggerCommand($command, $service, $vars);
     $title = craft()->amCommand->getReturnTitle();
     $message = craft()->amCommand->getReturnMessage();
     $redirect = craft()->amCommand->getReturnUrl();
     $action = craft()->amCommand->getReturnAction();
     $commands = craft()->amCommand->getReturnCommands();
     $delete = craft()->amCommand->getDeleteStatus();
     // Overwrite result with overwritten commands?
     if ($commands) {
         $result = $commands;
     }
     // Return the result
     if ($result === false) {
         $this->returnJson(array('success' => false, 'message' => $message ? $message : Craft::t('Couldn’t trigger the command.')));
     } else {
         $this->returnJson(array('success' => true, 'title' => $title, 'message' => $message, 'result' => $result, 'redirect' => $redirect, 'isNewSet' => !is_bool($result), 'isAction' => $action, 'deleteCommand' => $delete));
     }
 }
开发者ID:transomdesign,项目名称:transom-craft-starter,代码行数:29,代码来源:AmCommand_CommandsController.php

示例14: actionCropSaveAction

 public function actionCropSaveAction()
 {
     $this->requireAjaxRequest();
     $this->requireAdmin();
     try {
         $x1 = craft()->request->getRequiredPost('x1');
         $x2 = craft()->request->getRequiredPost('x2');
         $y1 = craft()->request->getRequiredPost('y1');
         $y2 = craft()->request->getRequiredPost('y2');
         $source = craft()->request->getRequiredPost('source');
         $assetId = craft()->request->getPost('assetId');
         // We're editing an existing image
         if ($assetId) {
             $asset = craft()->assets->getFileById($assetId);
             $result = craft()->imageResizer->crop($asset, $x1, $x2, $y1, $y2);
             if ($result) {
                 $this->returnJson(array('success' => true));
             } else {
                 $this->returnErrorJson(Craft::t('Could not crop the image.'));
             }
         }
     } catch (Exception $exception) {
         $this->returnErrorJson($exception->getMessage());
     }
     $this->returnErrorJson(Craft::t('Something went wrong when processing the image.'));
 }
开发者ID:kcolls,项目名称:ImageResizer,代码行数:26,代码来源:ImageResizerController.php

示例15: actionSaveRule

 /**
  * Saves a new or existing rule.
  *
  * @return null
  */
 public function actionSaveRule()
 {
     $this->requirePostRequest();
     $rule = new AutoExpire_RuleModel();
     $rule->id = craft()->request->getPost('id');
     $rule->name = craft()->request->getPost('name');
     $rule->sectionId = craft()->request->getPost('sectionId');
     $rule->dateTemplate = craft()->request->getPost('dateTemplate');
     $rule->allowOverwrite = craft()->request->getPost('allowOverwrite');
     // Extract the entry type and the field from sections array
     $sections = craft()->request->getPost('sections');
     if (isset($sections[$rule->sectionId])) {
         $rule->entryTypeId = $sections[$rule->sectionId]['entryTypeId'];
         $rule->fieldHandle = $sections[$rule->sectionId][$rule->entryTypeId]['fieldHandle'];
     }
     // Did it save?
     if (craft()->autoExpire->saveRule($rule)) {
         craft()->userSession->setNotice(Craft::t('Rule saved.'));
         $this->redirectToPostedUrl();
     } else {
         craft()->userSession->setError(Craft::t('Couldn’t save rule.'));
     }
     // Send the rule back to the template
     craft()->urlManager->setRouteVariables(array('rule' => $rule));
 }
开发者ID:carlcs,项目名称:craft-autoexpire,代码行数:30,代码来源:AutoExpireController.php


注:本文中的Craft类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。