Yii2 Dropzone.js init not working
I am using yii2 with dropzonejs (perminder-klair / yii2-dropzone)
When I want to initialize a view with some data, I got this error, It seems that the init call has not completed.
Mistake
dropzone.min.js:1 Uncaught TypeError: this.options.init.call is not a function
at c.init (dropzone.min.js:1)
at new c (dropzone.min.js:1)
at HTMLDocument.<anonymous> (index.php?r=branches/upload:672)
at fire (jquery.js:3187)
at Object.fireWith [as resolveWith] (jquery.js:3317)
at Function.ready (jquery.js:3536)
at HTMLDocument.completed (jquery.js:3552)
my dropzonejs
<?= \kato\DropZone::widget([
'autoDiscover' => false,
'options' => [
'init' => "function(file){alert( ' is removed')}",
'url'=> 'index.php?r=branches/upload',
'maxFilesize' => '2',
'addRemoveLinks' =>true,
'acceptedFiles' =>'image/*',
],
'clientEvents' => [
'complete' => "function(file){console.log(file)}",
// 'removedfile' => "function(file){alert(file.name + ' is removed')}"
'removedfile' => "function(file){
alert('Delete this file?');
$.ajax({
url: 'index.php?r=branches/rmf',
type: 'GET',
data: { 'filetodelete': file.name}
});
}"
],
]);
?>
source to share
This plugin uses a function Json::encode
for encoding parameters, and because of this it is init
encoded as a string in the code . The string is not a function .
You can just use JsExpression on the function javascript
to prevent this from happening .
When using yii \ helpers \ Json :: encode () or yii \ helpers \ Json :: htmlEncode () to encode a value, JsonExpression objects will be treated specifically and encoded as a JavaScript expression instead of a string .
This code should work.
<?= \kato\DropZone::widget([
'autoDiscover' => false,
'options' => [
'init' => new JsExpression("function(file){alert( ' is removed')}"),
'url'=> 'index.php?r=branches/upload',
'maxFilesize' => '2',
'addRemoveLinks' =>true,
'acceptedFiles' =>'image/*',
],
'clientEvents' => [
'complete' => "function(file){console.log(file)}",
// 'removedfile' => "function(file){alert(file.name + ' is removed')}"
'removedfile' => "function(file){
alert('Delete this file?');
$.ajax({
url: 'index.php?r=branches/rmf',
type: 'GET',
data: { 'filetodelete': file.name}
});
}"
], ]); ?>
source to share
it looks like this part in your options overwrites the Dropzone.js function init
:
'init' => "function(file){alert( ' is removed')}",
The Yii2 plugin you are using simply encodes an array of options:
Json::encode($this->options)
So your init is not function
, this string
is how it is:
var options = { "init" : "function(file){alert( ' is removed')}" }
Can't set a parameter init
in this php plugin.
Edit: Thanks @CooPer for the fix, Yii2 is not my favorite framework so I am not very familiar with it. This is a good decision.
source to share