Skip to content

Instantly share code, notes, and snippets.

@mdcpepper
Last active August 29, 2015 14:19
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mdcpepper/548fd04939e040507960 to your computer and use it in GitHub Desktop.
Save mdcpepper/548fd04939e040507960 to your computer and use it in GitHub Desktop.
<?php
namespace Craft;
class EntryTypeSourcesPlugin extends BasePlugin
{
public function getName()
{
return Craft::t('Entry Type Sources');
}
public function getVersion()
{
return '1.1';
}
public function getDeveloper()
{
return 'Mike Pepper';
}
public function getDeveloperUrl()
{
return 'http://twitter.com/mdcpepper';
}
protected function defineSettings()
{
return array(
'entryTypes' => array(AttributeType::Mixed, 'default' => array()),
);
}
public function getSettingsHtml()
{
$entryTypes = $this->_getEntryTypes()->queryAll();
$selectedEntryTypes = array();
foreach ($this->getSettings()->entryTypes as $entryType)
{
$selectedEntryTypes[] = $entryType['value'];
}
return craft()->templates->renderMacro('_includes/forms', 'checkboxSelectField', array(
array(
'first' => true,
'label' => 'Entry Types',
'instructions' => 'Choose which entry types should be included in entry source lists.',
'name' => 'entryTypes',
'options' => $entryTypes,
'values' => $selectedEntryTypes,
)
));
}
public function prepSettings($settings)
{
if ('*' == $settings['entryTypes'])
{
$settings['entryTypes'] = $this->_getEntryTypes()->queryAll();
}
else
{
$settings['entryTypes'] = $this->_getEntryTypes()
->where(array('in', 'entrytypes.id', $settings['entryTypes']))
->queryAll();
}
return $settings;
}
public function modifyEntrySources(&$sources, $context)
{
$settings = $this->getSettings();
$entryTypesBySectionId = array();
foreach ($settings->entryTypes as $entryType)
{
$entryTypesBySectionId[$entryType['sectionId']][] = $entryType;
}
foreach ($sources as $sourceKey => $source)
{
if (strpos($sourceKey, 'section:') === 0)
{
list($section, $sectionId) = explode(':', $sourceKey);
if (array_key_exists($sectionId, $entryTypesBySectionId))
{
if (!isset($sources[$sourceKey]['nested']))
{
$sources[$sourceKey]['nested'] = array();
}
foreach($entryTypesBySectionId[$sectionId] as $entryType)
{
$sources[$sourceKey]['nested']['entrytype:'.$entryType['value']] = array(
'label' => $entryType['label'],
'criteria' => array('type' => $entryType['value'], 'editable' => true),
);
}
}
}
}
}
private function _getEntryTypes()
{
return craft()->db->createCommand()
->select('entrytypes.id as value, entrytypes.name as label, entrytypes.sectionId')
->from('entrytypes entrytypes')
->join('sections sections', 'sections.id = entrytypes.sectionId')
->where("sections.type != 'single'");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment