12

I have a Global Set called "Settings" (handle = 'settings'); Within that I have a text field called "Address" (handle = 'address').

I have a function in my Plugin and I'd like to get the Address data.

In the front-end I would write this:

{{ settings.address }}

How can I get the same information in my plugin with PHP?

I've got as far as this:

$address = craft()->elements->getCriteria(ElementType::GlobalSet);

When I var_dump this array, I can see the address string. But I can't figure out how to filter down to the address correctly.

Thanks

22

You can use the GlobalsService service available with craft()->globals like so:

// Get the settings global set
$settings = craft()->globals->getSetByHandle('settings');

// Access the address field
var_dump($settings->address)

Or you could use ElementCriteria as you suggested:

// Get the GlobalSet element critera
$criteria = craft()->elements->getCriteria(ElementType::GlobalSet);
// Set the handle you want
$criteria->handle = 'settings';
// Find the settings set
$settings = $criteria->first();

// Access the address field
var_dump($settings->address)

You can access all fields on the $settings variable using this synthax.

Mario

  • Thanks for the quick and concise answer Mario. They both worked like a charm. I think I'll use use your first suggestion though... as it's more tidy and does exactly what I need. – Mark Notton Aug 5 '14 at 13:08
3

If you want to get all values from a global set without having to specify each field handle you can do something like this:

$set = craft()->globals->getSetByHandle('globalHandleHere');
$fieldLayoutFields = $set->getFieldLayout()->getFields();

foreach ($fieldLayoutFields as $fieldLayoutField) {
    $field = craft()->fields->getFieldById($fieldLayoutField->fieldId);   
    $value = $set->getContent()[$field->handle];

    // Do whatever with $value here.
}
  • 1
    Thanks @Ragnarsson for adding a good answer to an older post. I can see this being useful for something I'm working on right now oddly enough. Thanks again! – Mark Notton Sep 6 '16 at 9:58
  • Glad I could help Mark. Remember that depending on the fieldtypes in the global you might have to extend this code. The code above would return null for assets for example. You might want to switch over the $field->type and write code that can handle all expected types. – Ragnarsson Sep 6 '16 at 11:25

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.