I am creating a plugin that is based on images the admin will upload some sort of images in plugin settings not sure how to creat image field setting in plugin


To have asset selection and upload in your twig, you can use elementSelectField

the code i wrote here is just sample and definitely you need to review, consider security and validation

firstly you should have an extra public attribute to keep selected asset on settings model:

class Settings extends Model
    public $imageId = [];

in your settings.twig template you use elementSelectField like:

{{ forms.elementSelectField({
    label: "image",
    id: "imageId",
    name: "imageId",
    viewMode: "list",
    elementType: 'craft\\elements\\Asset', //limit to to asset element type
    selectionLabel: "Add Images",
    sources: ['folder:'~folderUid], //if you want to limit it to one volume folder not all volumes
    required: false,
    errors: settings.getErrors('imageId'),
    limit: 2, // if you want maximum two images 
    elements: images,  // at first it is null, then we pass selected assets as images 
    criteria: { kind: 'image'} // because you want only images
}) }}

in settingsHtml() method:

use craft\records\VolumeFolder;
protected function settingsHtml()
    $settings = $this->getSettings();
    // to load currently selected assets 
    $images = [];
    if ($settings->imageId) {
        foreach ($settings->imageId as $imgId) {
            $images[] = Craft::$app->elements->getElementById($imgId);
    //to limit asset selection to one folder
    $volume = Craft::$app->volumes->getVolumeByHandle('volumeHandle');//it could be the volume handle you created before
    $volFolderRecord = VolumeFolder::findOne([
        'volumeId' => $volume->id
    $folderUid = $volFolderRecord->uid;
    return \Craft::$app->getView()->renderTemplate(
            'settings' => $settings,
            'images' => $images
            'folderUid' => $folderUid

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.