You can create a new field with these functions. Note: this is a very basic example, you would usually want to do this with a template but I don't have much time
class FolderAssetField extends Field {
// Static Methods
// =========================================================================
public $folderId;
/**
* Returns the display name of this class.
*
* @return string The display name of this class.
*/
public static function displayName(): string{
return 'Folder';
}
/**
* @param $value
* @param ElementInterface|null $element
* @return string
*/
public function getInputHtml($value, ElementInterface $element = null): string
{
$allFileModels = \craft\records\VolumeFolder::find()->all();
$string = 'select a folder<br><select name="' . $this->handle . '">';
/** @var VolumeFolder $folder */
foreach ($allFileModels as $folder){
$selected = ((int)$value === $folder->id)? 'selected="selected' : '';
$string .= '<option ' . $selected . ' value="' . $folder->id . '">' . $folder->name . '</option>';
}
$string .= '</select>';
return $string;
}
}
Your field will then contain the folderId
of the selected folder. You can then get all assets for this folder with
/** @var AssetQuery $assetQuery */
$assetQuery = \craft\elements\Asset::find();
$assets = $assetQuery->folderId($value)->all();
or in Twig
{% set assets = craft.assets.folderId(entry.fieldHanlde).all() %}
{% for file in assets %}
{{ file.title }}<br>
{% endfor %}
You could also use the normalizeValue
function to prepare this Query. The Redactor plugin has some good examples here