7

I am building a plugin that's uses an enum for custom statuses. The statuses are integrated within my plugin with the exception of changing the status in my template code.

pluginname/enums/PluginStatus.php

<?php
namespace Craft;

class PluginNameStatus
{
    const Approved = 'approved';
    const Denied   = 'denied';
    const Pending  = 'pending';
}

What is the best method to grab the enum values and display those in a select field for my edit template? All of my templates are rendered via controller actions so I am thinking that assigning the enums to an array and passing to the templates as $variables might be the most practical method.

pluginname/controllers/PluginNameController.php

<?php
namespace Craft;

class PluginNameController extends BaseController
{
    public function actionShowIndex()
    {
        $variables['customStatuses'] = array(
            PluginStatus::Approved => 'Approved',
            PluginStatus::Denied   => 'Denied',
            PluginStatus::Pending  => 'Pending',
        ), 
        $this->renderTemplate('pluginname/_edit', $variables);
    }
}
5

Right now that's probably the best way to do it.

For Craft 2.2, I just added a static getConstants() method to BaseEnum, so you can do can do a PluginStatus::getConstants() call that will return an array with a key => value pair of the enum options and their values that should make that cleaner.

| improve this answer | |
  • 1
    Glad you're easily impressed. :) – Brad Bell Jul 15 '14 at 4:47
  • 1
    Anything Brad does impresses me as I know getting you to do anything takes an act of God... ;) But seriously, awesome to hear. – Jason McCallister Jul 15 '14 at 4:48
2

I found an issue importing the enums via the init() method. You will receive a Fatal error: Class 'Craft\PluginStatus' not found on install. It seems during the install the init() method is not called in time to include the custom enums.

However, this works as its called immediately.

pluginname/PluginNamePlugin.php

<?php
namespace Craft;

// include enums for custom statuses
include(dirname(__FILE__) . '/enums/PluginStatus.php');

class PluginNamePlugin extends BasePlugin
{
    // etc
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.