Symfony UX Dropzone
Symfony UX Dropzone 是一個 Symfony 套件,為 Symfony 表單中的檔案輸入提供輕量級的拖放區域。它是 Symfony UX 計畫 的一部分。
它允許訪客將檔案拖放到容器中,而無需瀏覽電腦尋找檔案。
安裝
注意
在開始之前,請確保您的應用程式中已設定 StimulusBundle。
使用 Composer 和 Symfony Flex 安裝套件
1
$ composer require symfony/ux-dropzone
如果您使用 WebpackEncore,請安裝您的 assets 並重新啟動 Encore (如果您使用 AssetMapper 則不需要)
1 2
$ npm install --force
$ npm run watch
使用方式
Symfony UX Dropzone 最常見的用法是將其用作原生 FileType 類別的直接替代品
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// ...
use Symfony\UX\Dropzone\Form\DropzoneType;
class CommentFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// ...
->add('photo', DropzoneType::class)
// ...
;
}
// ...
}
自訂設計
Symfony UX Dropzone 提供預設樣式表以簡化使用。您可以停用它以新增您自己的設計(如果需要)。
在 assets/controllers.json
中,將 @symfony/ux-dropzone/dist/style.min.css
的自動導入切換為 false
,以停用預設樣式表
1 2 3 4 5 6 7 8 9 10 11 12 13 14
{
"controllers": {
"@symfony/ux-dropzone": {
"dropzone": {
"enabled": true,
"fetch": "eager",
"autoimport": {
"@symfony/ux-dropzone/dist/style.min.css": false
}
}
}
},
"entrypoints": []
}
注意
注意:您應該將值設為 false
,而不是移除該行,這樣 Symfony Flex 未來才不會嘗試再次新增該行。
完成後,將不再使用預設樣式表,您可以基於 Dropzone 實作您自己的 CSS。
擴展預設行為
Symfony UX Dropzone 允許您使用自訂 Stimulus 控制器擴展其預設行為
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
// mydropzone_controller.js
import { Controller } from '@hotwired/stimulus';
export default class extends Controller {
connect() {
this.element.addEventListener('dropzone:connect', this._onConnect);
this.element.addEventListener('dropzone:change', this._onChange);
this.element.addEventListener('dropzone:clear', this._onClear);
}
disconnect() {
// You should always remove listeners when the controller is disconnected to avoid side-effects
this.element.removeEventListener('dropzone:connect', this._onConnect);
this.element.removeEventListener('dropzone:change', this._onChange);
this.element.removeEventListener('dropzone:clear', this._onClear);
}
_onConnect(event) {
// The dropzone was just created
}
_onChange(event) {
// The dropzone just changed
}
_onClear(event) {
// The dropzone has just been cleared
}
}
然後在您的表單中,將您的控制器新增為 HTML 屬性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// ...
use Symfony\UX\Dropzone\Form\DropzoneType;
class CommentFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// ...
->add('photo', DropzoneType::class, [
'attr' => ['data-controller' => 'mydropzone'],
])
// ...
;
}
// ...
}
向後相容性承諾
此套件旨在遵循與 Symfony 框架相同的向後相容性承諾:https://symfony.dev.org.tw/doc/current/contributing/code/bc.html