Hi,
At the moment, I am having trouble using the elements of an array that I pass into view from its controller. Here is the code for the controller
class FileController extends Controller{
public function actionUpload()
{
// create new model
$model = new UploadFile();
if(Yii::$app->request->isPost){
$model->file = UploadedFile::getInstance($model, 'file');
// if upload is successful
if($name = $model->upload()){
// create a new row for db to store the file;
$db = new Files(); // this model accesses the files table in the yii2basic database
// attributes
$db->size = $model->getSize();
$db->type = $model->getType();
$db->realname = $name;
$db->created = date('Y-m-d h:m:s');
$db->save();
// redirect to the same page to avoid resubmission
$this->redirect(array('file/upload'));
return;
};
}
// get the files logged in database, display it in upload view
$files = Files::find()->indexBy('id')->all();
// renders view
return $this -> render('upload', ['model' => $model], array('filesdb' => $files));
}
}
Here’s the code for the corresponding view
<body>
<button class = "btn btn-default btn-sm" data-toggle = "modal" data-target = ".fileUpload">
Add Document </button>
<div class = "modal fade fileUpload">
<div class = "modal-dialog">
<?php $form = ActiveForm::begin([
// set other attributes for the form here if needed
'options' => ['enctype' => 'multipart/form-data']
]); ?>
<div class = "modal-content">
<div class = "modal-header">
<button type = "button" class = "close" data-dismiss = "modal">
<span aria-hidden = "true">× </span><span class = "sr-only"> Close</span>
</button>
<h5 class = "modal-title"> Add Document </h5>
</div>
<div class= "modal-body">
<?= $form->field($model, 'file')->fileInput() ?>
</div>
<div class= "modal-footer">
<input id = "file-upload" type="submit" name = "submit" value = "Send">
<label for = "file-upload" class = "custom-upload">Send</label>
<button type = "button" class = "btn btn-default btn-sm" data-dismiss = "modal">
Close
</button>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</body>
<body>
<div class="container-fluid">
<?php echo $filesdb; ?>
</div>
</body>
When using $filesdb in view I am getting the error [color="#FF0000"]undefined variable[/color] $filesdb. I have tried multiple methods of accessing the array such as the for each loop but none seems to work. I am not sure why it would be undefined. When using a simple variable instead of an array everything works.I am able to access $model and use it.
Thanks for the help!