10

I'm working on a plugin with its own element type, I'm trying to add custom statuses to the element type. What is the best way to proceed? I have hasStatuses set to true and getStatuses is where I would set them.. But what should the array look like thats returned?

UserElementType returns this:

/**
 * Returns all of the possible statuses that elements of this type may have.
 *
 * @return array|null
 */
public function getStatuses()
{
    return array(
        UserStatus::Active    => Craft::t('Active'),
        UserStatus::Pending   => Craft::t('Pending'),
        UserStatus::Locked    => Craft::t('Locked'),
        UserStatus::Suspended => Craft::t('Suspended'),
        UserStatus::Archived  => Craft::t('Archived')
    );
} 
  • So I did a little bit more research and noticed that the UserStatus is an enum. Is this a possibility to implement in a Craft plugin? – Jason McCallister Jul 10 '14 at 8:05
12

All you need to return from the getStatuses() method is an associative array() where the key represents the status name and the value represents the status label, more or less.

An example might be a set of statuses for a Payment element type:

public function getStatuses()
{
    return array(
        'captured' => Craft::t('Captured'),
        'canceled' => Craft::t('Canceled'),
        'refunded' => Craft::t('Refunded'),
    );
}

Now, since it is likely that you'll be referring to and comparing against those statuses, it makes sense to give yourself a little extra insurance by creating a set of class constants instead of using plain strings.

That is exactly what Craft has done in the UserStatus class and you can achieve the same result in one of two ways.


1. Create your own class and define those constants

// plugin/enums/PluginPaymentStatus.php
namespace Craft;

class PluginPaymentStatus
{
    const CAPTURED = 'captured';
    const CANCELED = 'canceled';
    const REFUNDED = 'refunded';
}

// plugin/elementtypes/PluginElementType.php
public function getStatuses()
{
    return array(
        PluginPaymentStatus::CAPTURED => Craft::t('Captured'),
        PluginPaymentStatus::CANCELED => Craft::t('Canceled'),
        PluginPaymentStatus::REFUNDED => Craft::t('Refunded'),
    );
}

2. Create the status constants in your element type model if you have one


Note that if you go with option 1, you will need to import|include|require your "enum".

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.