Search code examples
phpmediashopware6uploadingcustom-field-type

How to set uploaded image (in category custom field) default location via plugin extension?


Please, how to set uploaded image (in category custom field) default location via plugin extension?

My plugin extension will create new folder after installation, but when i am uploading my custom image via category custom field, this media is located in root directory in media

I need to save it directly, to my created folder - for example: media/myImageDirectoryForPlugin/

I know exactly what ID has my folder. But i don't know, how link that ID with my Custom Field element for uploading images.

i checked documentation - here: Own media folder

Customers must create own media folders or use existing ones to upload images.

Unfortunately, this information did not help me in any way :o)

Thank you very much for help.

I tried to set it in my *.php where i am creating my Folder and Custom Field, but with no luck.


Solution

  • You can't influence the directory path in the filesystem. The folders only exist on the database level, not in the actual filesystem. When you look at public/media you will find that the directory tree is generated using hashes and doesn't relate to the folders in the administration.

    However, if you still want to use a custom folder for the sake of organization or want to use one of the pre-existing folders, you can. When you create the custom field you can provide additional properties for the component. For the sw-media-field component you can use the defaultFolder property to define the folder to be used.

    When you create a custom folder, you can also provide data for the association to media_default_folder. That table has a column entity and that's the value you have to provide for the defaultFolder property of the custom field, so it will use the associated folder.

    // persist the custom folder
    $data = [
        'name' => 'my-custom-folder',
        'useParentConfiguration' => false,
        'configuration' => [],
        'defaultFolder' => [
            'associationFields' => [],
            'entity' => 'my_custom_entity',
        ],
    ];
    
    $this->getContainer()->get('media_folder.repository')
        ->create([$data], Context::createDefaultContext());
    
    // persist the custom field
    $data = [
        'name' => 'lorem_ipsum',
        'type' => CustomFieldTypes::TEXT,
        'customFieldSetId' => '...',
        'config' => [
            'componentName' => 'sw-media-field',
            'customFieldPosition' => 1,
            'customFieldType' => CustomFieldTypes::MEDIA,
            'defaultFolder' => 'my_custom_entity',
            'label' => [
                'en-GB' => 'lorem_ipsum',
                'de-DE' => 'lorem_ipsum',
            ],
        ],
    ];
    
    $this->getContainer()->get('custom_field.repository')
        ->create([$data], Context::createDefaultContext());