Hot answers tagged

22

My recommendation would be to go with Craft 2: A bird in the hand is worth two in the bush There is no doubt that Pixel & Tonic has turned their focus to Craft 3, but software projects are complex and often take longer than expected and Craft 3 currently only has speculative release dates. It has also had speculative release dates in the past. If ...


19

Saving Matrix fields programmatically got a lot easier in Craft 3 thanks to all the content refactoring. use craft\elements\Entry; use craft\elements\MatrixBlock; // Figure out the section & entry type $section = Craft::$app->sections->getSectionByHandle('news'); $entryTypes = $section->getEntryTypes(); $entryType = reset($entryTypes); // ...


19

To pull off the same functionality in Craft 3, you could use something like this: {entry.last().uri}/{parent.uri}/{slug}


16

First a bit of history: Craft 2 has a similar concept where it would store a unique random security key in craft/storage/runtime/validation.key. Alternatively, you could set the validationKey config setting if you wanted to provide your own key instead of use the one generated by Craft. Craft 2 would essentially only use this for encrypting cookie data in ...


16

For future reference, I had the same error and resolved it with Craft Support. In my case the project.yaml file got out of sync with what was in the database. Running craft project-config/rebuild from the project's root resolved the issue and allowed us to re-enable the plugins


15

I gave everything a try, but the only thing that worked for me was ensuring "Allow network access to MySQL" was ticked in MAMP. Screenshot: http://c42.co/Ur30EJ


15

The concept of localization has changed in Craft 3, there are not only locales anymore - now you have different sites and site groups. Example without multisite - only different locals You can get all available sites for an entry with {% set supportedSites = entry.getSupportedSites %} This will return you an array of all supported sites for the entry. {...


14

After playing with this a little further it seems the unixSocket setting is necessary to get this working so I added: 'unixSocket' => getenv('DB_SOCKET') To config/db.php and then added: DB_SOCKET="/Applications/MAMP/tmp/mysql/mysql.sock" To my .env file. After that, the installation will go through using the CLI. Perhaps there's still an option that ...


12

I finally figured out how to upload an asset, however I still don't understand why the insertFileByLocalPath has been removed. /** * @param UploadedFile $uploadedFile * @param int $folderId * @return Asset * @throws BadRequestHttpException * @throws UploadFailedException */ protected static function uploadNewAsset(UploadedFile $uploadedFile, $folderId)...


12

You can use Craft::getLogger()->log($message, $level, $category = 'application') It uses the Yii2 logger, you can change the $category to your plugin handle Edit: You can use the "short" syntax as well class reference Craft::warning($message, $category); or Craft::info($message, $category);


12

Craft::$app->getUser() returns only the user service/component. You should read the docs about that What you want is the current Identity Craft::$app->getUser()->getIdentity()


12

Add the linkNewTab config option to the Redactor config you're using: So, that would become something like: { "buttons": [...], "plugins": [...], "linkNewTab": true }


11

Here are some. Store Hours (P&T) match input Mandrill (P&T) Entry Count Minify (9/17/2016) MN Twig Perversion (9/19/2016) Stamp (9/21/2016) Inlin (9/21/2016) Mention more in the comments, and I will add to this list.


11

Just an additional note: If you want to append certain elements to your matrix field instead of overwriting them all you have to do /** @var \craft\fields\Matrix $field */ $field = Craft::$app->getFields()->getFieldByHandle('matrixField'); // get the existing matrixField Value, keep in mind, this is a Query and not an array $existingMatrixQuery = $...


11

With RC1 the rich text editor was moved to a plugin. You can find the Redactor editor (the previous richtext field) in the plugin store along with a new CKEditor editor as well. You can read about this in the docs, too: https://docs.craftcms.com/v3/changes-in-craft-3.html#rich-text-fields


11

There aren't specific User element save events in Craft 3, but you can listen to EVENT_AFTER_SAVE_ELEMENT and check if the element is a user like so: Event::on(\craft\services\Elements::class, \craft\services\Elements::EVENT_AFTER_SAVE_ELEMENT, function(Event $event) { if ($event->element instanceof \craft\elements\User) { // Do your thing. ...


11

You can set flash messages using yii\web\Session::setFlash(). The session component is available to templates via craft.app.session. {% do craft.app.session.setFlash('error', 'You’re not allowed to go there.') %} For convenience, Craft’s SessionBehavior class adds shortcut setError() and setNotice() methods to the session component as well. {% do craft....


10

Another perhaps simpler approach is to write to your own log file without using the Craft logger at all. $file = Craft::getAlias('@storage/logs/pluginhandle.log'); $log = date('Y-m-d H:i:s').' '.$message."\n"; \craft\helpers\FileHelper::writeToFile($file, $log, ['append' => true]); UPDATE: I released the Log To File Helper which provides a simple way ...


10

Edit 2 I came up with a far far far better approach after a little brainstorming. I'll keep my old answer here but you should probably just use the first snipped. In your main Pluginfile.php public static function log($message){ Craft::getLogger()->log($message, \yii\log\Logger::LEVEL_INFO, 'your-plugin-handle'); } public function init(){ $...


10

You can create a script to use the craft executable to sync your project config file ./craft project-config/sync


10

Whilst Doug's answer is useful for knowing the ins and outs of a particular event once you've found it, actually finding which events are available in Craft 3 in the current docs is not straight-forward. After a bit of digging, you'll find that most events are part of Craft's services - so head to the Class Reference and choose the most relevant service from ...


9

Ben's answer is excellent, and should be marked as correct. This is simply some additional information to reinforce the decision to use Craft 2. The current version of Craft 3 is a developer preview beta (thanks Simon)... This means that there are no implicit claims of stability, and anything could change at any time. Similarly, there is no guarantee that ...


9

There are two checkboxes in your user settings, go to your admin account -> preferences index.php?p=admin/myaccount and check the boxes This is covered in detail in the Profiling your Website with Craft CMS 3’s Debug Toolbar article


9

Another perhaps simpler approach is to write to your own log file without using the Craft logger at all. $file = Craft::getAlias('@storage/logs/pluginhandle.log'); $log = date('Y-m-d H:i:s').' '.$message."\n"; \craft\helpers\FileHelper::writeToFile($file, $log, ['append' => true]); UPDATE: This logic has been put into a helper class for modules and ...


9

These are the two approaches I usually choose from: Option 1: the 'default' Craft 3 way Create a .env file for every environment you create, and add it to your .gitignore file (if it's not yet in it). In this file, you put all environment-specific details; Craft, by default, will recognize and use those details. In your Craft config files, you can use the ...


9

You can use either an activeRecord for it $customer = Customer::find() ->where(['id' => 123]) ->one(); Or a query $rows = (new \craft\db\Query()) ->select(['id', 'email']) ->from('user') ->where(['last_name' => 'Smith']) ->limit(10) ->all();


8

Apparently I figured it out. Would still like a better way of doing this, but here's the solution I found to be working: In your Plugin class, you have to add a public $controllerMap array. For my example plugin above, here's what I would have to add to that $controllerMap array: use Very\Waffle\Controllers\SyrupController; class Plugin extends \craft\...


8

"Sites" in Craft 3 replaces the old "Locales" concept in Craft 2. There's not much documentation on them yet, but the setup process is virtually the same as it is in Craft 2 for locales. The main difference is that a "site" isn't necessarily tied to a language code, like it is in Craft 2. https://craftcms.com/news/craft-3-multi-site Update: ...


8

So as of Craft CMS 3 RC7, they added a new alias() Twig function. So what you can do is something like this in your general.php: 'aliases' => [ '@basePath' => getenv('CRAFTENV_BASE_PATH'), '@baseUrl' => getenv('CRAFTENV_BASE_URL'), ], (or whatever/however you want to set them). These aliases can be used in sites’ Base URL settings, ...


8

There is no real difference between a "normal" ajax request and an ajax request in Craft. You just leave the url blank, and insert an action parameter for your route. Craft 3 uses snake-case routes instead of camelCase. So when you want to access your plugin you would do. action = "plugin-handle/controller-name/function-name I full example as a CP request ...


Only top voted, non community-wiki answers of a minimum length are eligible