2

I'm trying to create a plugin that adds a tab full of fields to entry types but I can't seem to get it working. I tried assembleLayout but that replaced all the fields with my new fields rather than adding a new tab to them.

I'm trying different combinations of FieldLayoutTabModel->setFields() but that throws an error about a fieldId property which leads me to believe I don't quite have the data types right. Any help would be appreciated.

7

I eventually figured this out. Here's the code that's working for me:

$newFields = array(
  0 => '12', // $field->fieldId
  1 => '15'  // $field->fieldId
);

// First we get all sections and loop through them
$allSections = craft()->sections->getAllSections();
foreach ($allSections as $section)
{
  // Then we get all EntryTypes of each section and loop through those
  $sectionEntryTypes = $section->getEntryTypes();
  foreach ($sectionEntryTypes as $entryType) 
  {
    // Grab the current layout and tabs
    $currentLayout = $entryType->getFieldLayout();
    $currentTabs = $currentLayout->getTabs();

    // This will the array passed to assembleLayout
    $postedFieldLayout = array();

    // Loop through each tab and build our array
    foreach ($currentTabs as $tab) {
      $fields = $tab->getFields();
      foreach ($fields as $field) {
        $postedFieldLayout[$tab->name][] = $field->fieldId;
      }
    }

    // Append the new fields we want to show to that array
    $postedFieldLayout['newFields'] = $this->newFields;
    $requiredFields = array();

    // Assemble the layout
    $fieldLayout = craft()->fields->assembleLayout($postedFieldLayout, $requiredFields);
    $fieldLayout->type = ElementType::Entry;
    $entryType->setFieldLayout($fieldLayout);

    // Save it
    if (craft()->sections->saveEntryType($entryType))
    {
      Craft::log('Successfully appended fields.');
    }
    else 
    {
      Craft::log('Could not append the fields.', LogLevel::Warning);
    }
  }
}
| 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.