1

I'm currently working on creating a full-sized Edit Page for my own Element Type.

I created a elementSelectField and wanted to know if you guys have some advise or good articles to read on that matter. Right now I'm crawling my way through the craft code for reverence and i am not sure if I'm doing this correctly :)

{% set section = craft.app.sections.getSectionByHandle('days') %}
{% set elementType = craft.app.elements.getElementTypeByRefHandle('Entry') %}

{{ forms.elementSelectField({
        label: 'Day'|t('app'),
        instructions: 'The day the cookie belongs to'|t('app'),
        id: 'day',
        name: 'day',
        elementType: elementType,
        selectionLabel: "Choose a day"|t('app'),
        sources: ['section:'~section.id],
        criteria: '',
        elements: elementType,
        viewMode: 'list',
        limit: 1,
    })
}}

I think this is Ok? Sending the form to my controller and dumping it there, the selectfield's value array contains only the choosen entry's id.

1

Yes this is correct. The best documentation you can find is the source code, so looking at it is usually the way to go. Craft stores all relations with an array of element ids.

When you have a BaseRelationField in your elements field layout you'll store the value - even if it's a single value - like

$element->setFieldValue('day', [1]); //<- note, always pass an array

(or the faster variant)

$fieldsLocation = Craft::$app->getRequest()->getParam('fieldsLocation', 'fields');
$element->setFieldValuesFromRequest($fieldsLocation);

If you don't use a field layout and store your relations in a custom table/column you'll have to find a way that fits your requirements

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.