Take the 2-minute tour ×
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It's 100% free, no registration required.

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);
    }
}
share|improve this question

2 Answers 2

up vote 4 down vote accepted

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.

share|improve this answer
    
You made my night, thank you! –  Jason McCallister Jul 15 at 4:47
1  
Glad you're easily impressed. :) –  Brad Bell Jul 15 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 at 4:48
    
+1 for the accidental feature request! –  Lindsey D Jul 15 at 4:55

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
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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