1

Can anyone suggest on how to programatically save fields to a GlobalSet? I’ve been following this: Programatically Adding Fields to a Layout

But, doesn’t seem to work with a global?

I am doing the following :

  • Create a new field group - works
  • Assign fields to field group - works
  • Create global set - works
  • Create field layout - works
  • Create field layout tab - works
  • Set fields to layout tab - nope

.

// get all the fields from company info fieldgroup
$Fields = $FieldGroup->getFields();
// Get field layout
$GlobalSetLayout = $GlobalSet->getFieldLayout();


// Create tab model
$GlobalSetLayoutTab = new FieldLayoutTabModel();
$layout = craft()->fields->getLayoutByType(ElementType::GlobalSet);
$GlobalSetLayoutTab->setLayout($layout);
$GlobalSetLayoutTab->setFields($Fields);

// Set the tab's fields
$GlobalSetLayoutTab->setFields($fields);

// setTabs() expects an array
$layoutTabs[] = $GlobalSetLayoutTab;

// Now, set the tabs back in the layout.
$layout->setTabs($layoutTabs);

Not sure if part of the issue is because Globals don’t exactly have a “tab”, but looking at others in the database it does seem to have one with the name “Content”

2

Something like this should work:

// Generate name and handle.
$globalSetName = "My Global Set";
$globalSetHandle = lcfirst(str_replace(" ","", ucwords($globalSetName)));

// Create a global set
$globalSet= new GlobalSetModel();
$globalSet->name = $globalSetName;
$globalSet->handle = $globalSetHandle;

// get all the fields from  fieldgroup
$fields = $fieldGroup->getFields();

// Get ids of the fields.
$fieldIds = array();
foreach ($fields as $field)
{
    $fieldIds[] = $field->id;
}

// Assemble the field layout
$globalSetLayout = craft()->fields->assembleLayout(
    array(
        'Content' => $fieldIds,
    )
);

// Set the field layout type.
$globalSetLayout->type = ElementType::GlobalSet;

// Set field layout on global set.
$globalSet->setFieldLayout($globalSetLayout);

// Save global set.
craft()->globals->saveSet($globalSet);
| improve this answer | |
  • Works perfect thank you Brad, just needed to change foreach ($fields $field) to foreach ($fields as $field) – joep Aug 16 '17 at 8:11
  • 1
    Oops... fixed!! – Brad Bell Aug 16 '17 at 19:37

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.