Best way to have a predefined set of specific but re-orderable elements. #15639
-
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Interesting question. It seems like building this on relation fields is probably the most flexible, though it will require you to create new sections/entries even for the simpler use cases like your gallery page sections. I’ve just added With that, you could register a custom field type that extends namespace modules\foo\fields;
use craft\base\ElementInterface;
use craft\elements\db\ElementQueryInterface;
use craft\elements\Entry;
use craft\fields\Entries;
use craft\helpers\Cp;
class StaticEntries extends Entries
{
public static function displayName(): string
{
return 'Static Entries';
}
protected function inputTemplateVariables(array|ElementQueryInterface $value = null, ?ElementInterface $element = null): array
{
$variables = array_merge(parent::inputTemplateVariables($value, $element), [
'allowAdd' => false,
'allowRemove' => false,
]);
// make sure all the expected entries are selected
$ids = array_map(fn(Entry $entry) => $entry->getCanonicalId(), $variables['elements']);
$missingEntries = Entry::find()
->section('services')
->id(['not', ...$ids])
->site(Cp::requestedSite())
->all();
array_push($variables['elements'], ...$missingEntries);
return $variables;
}
} use craft\events\RegisterComponentTypesEvent;
use craft\services\Fields;
use modules\foo\fields\StaticEntries;
use yii\base\Event;
Event::on(Fields::class, Fields::EVENT_REGISTER_FIELD_TYPES, function(RegisterComponentTypesEvent $event) {
$event->types[] = StaticEntries::class;
}); You could either create a new field type like that for each individual use case, or put some work into making it a bit more customizable, e.g. based on the configured source settings. |
Beta Was this translation helpful? Give feedback.
Interesting question. It seems like building this on relation fields is probably the most flexible, though it will require you to create new sections/entries even for the simpler use cases like your gallery page sections.
I’ve just added
allowAdd
andallowRemove
settings to element select inputs (which relation fields use internally) for Craft 5.4: 0bf41d9With that, you could register a custom field type that extends
craft\fields\Entries
, and sets those two settings tofalse
, while also populating the selected entries with any missing entries, to ensure all possible entries are always selected when viewing the field.