File Upload with model

I can’t seem to get file upload working and would appreciate a helping hand as I’m sure I’m missing something obvious.

<?php
namespace backend\models;

use yii\base\Model;

use Yii;

/**
 * This is the model class for table "clients_documents".
 *
 * @property int $DocumentId
 * @property int $ClientId
 * @property int $DocumentCategoryId
 * @property string $Filename
 * @property string $Ext
 * @property string $Mime
 * @property int $Size
 * @property int $UserId
 * @property string $dtCreation
 * @property string $dtModification
 *
 * @property ProjectsLegs $leg
 * @property User $user
 * @property LstDocumentCategories $documentCategory
 */
class ClientsDocuments extends \yii\db\ActiveRecord
{
    /**
     * @var UploadedFile
     */
    public $UploadFile;  //Form File Input

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'clients_documents';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['ClientId', 'DocumentCategoryId', 'UserId'], 'required'],
            [['ClientId', 'DocumentCategoryId', 'Size', 'UserId'], 'integer'],
            [['dtCreation', 'dtModification', 'UploadFile'], 'safe'],
            [['Filename'], 'string', 'max' => 255],
            [['Ext', 'Mime'], 'string', 'max' => 10],
            [['ClientId'], 'exist', 'skipOnError' => true, 'targetClass' => Clients::className(), 'targetAttribute' => ['ClientId' => 'ClientId']],
            [['UserId'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['UserId' => 'id']],
            [['DocumentCategoryId'], 'exist', 'skipOnError' => true, 'targetClass' => LstDocumentCategories::className(), 'targetAttribute' => ['DocumentCategoryId' => 'DocumentCategoryId']],
            [['UploadFile'], 'file'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'DocumentId' => Yii::t('app', 'ID'),
            'ClientId' => Yii::t('app', 'Client'),
            'DocumentCategoryId' => Yii::t('app', 'Category'),
            'Filename' => Yii::t('app', 'File'),
            'UploadFile' => Yii::t('app', 'File'),
            'Ext' => Yii::t('app', 'Ext'),
            'Mime' => Yii::t('app', 'Mime'),
            'Size' => Yii::t('app', 'Size'),
            'UserId' => Yii::t('app', 'User ID'),
            'dtCreation' => Yii::t('app', 'Created'),
            'dtModification' => Yii::t('app', 'Modified'),
        ];
    }

the view

<?php
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\bootstrap\ActiveForm; //used to enable bootstrap layout options

use backend\models\LstDocumentCategories;

/* @var $this yii\web\View */
/* @var $model backend\models\ClientsDocuments */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="clients-documents-form">

    <?php 
        $form = ActiveForm::begin([
            'id'=>$model->formName(),
            'options' => [
                'enctype' => 'multipart/form-data' //required for file uploading!
            ]
        ]);
    ?>
    <div class="modal-body">
        <div class="row">
            <?php 
                echo $form->field($model, 'ClientId',
                [
                    'template' => '<div class="col-sm-2">{label}</div><div class="col-sm-2">{input}{error}</div>',
                    'labelOptions' => [
                        'class'=>'control-label'
                    ],
                ])->textInput() 
            ?>
        </div>
        <div class="row"> 
            <?= $form->field($model, 'DocumentCategoryId',
                    [
                        'template' => '<div class="col-sm-2">{label}</div><div class="col-sm-4">{input}{error}</div>',
                        'labelOptions' => [
                            'class'=>'control-label'
                        ],
                    ])
                    ->dropDownList(
                        ArrayHelper::map(
                                LstDocumentCategories::find()
                                    ->where(['DocumentSubjectId' => 1]) //Clients only!
                                    ->orderBy(['Category' => SORT_ASC,])
                                    ->all(),
                                'DocumentCategoryId',
                                'Category'
                        ),
                        [
                            'prompt'=>'Select a Category ...',
                        ]
                    )
            ?>
        </div>
        <div class="row"> 
            <?php
                echo $form->field($model, 'UploadFile')->fileInput();
            ?>
        </div>
    </div>
    <div class="modal-footer">
        <div class="row">
            <div class="col-sm-4">
            </div>
            <div class="col-sm-4">
                <?php // echo Html::submitButton($model->isNewRecord ? "<span class='glyphicon glyphicon-floppy-disk' aria-hidden='true'></span> ".Yii::t('app', 'Create') : "<span class='glyphicon glyphicon-floppy-disk' aria-hidden='true'></span> ".Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success form-cmd center-block' : 'btn btn-primary form-cmd center-block', 'data-dismiss'=>"modalPopup3", 'id' => 'closeButton3']) ?>
                <?php echo Html::submitButton($model->isNewRecord ? "<span class='glyphicon glyphicon-floppy-disk' aria-hidden='true'></span> ".Yii::t('app', 'Create') : "<span class='glyphicon glyphicon-floppy-disk' aria-hidden='true'></span> ".Yii::t('app', 'Close'), ['class' => $model->isNewRecord ? 'btn btn-success form-cmd center-block' : 'btn btn-primary form-cmd center-block']) ?>
            </div>
            <div class="col-sm-4">
            </div>
        </div>
    </div>
    <?php ActiveForm::end(); ?>
</div>

My controller

<?php
namespace backend\controllers;

use Yii;
use backend\models\ClientsDocuments;
use backend\models\ClientsDocumentsSearch;
use yii\web\Controller;
use yii\web\UploadedFile;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

define('DS', DIRECTORY_SEPARATOR);

/**
 * ClientsDocumentsController implements the CRUD actions for ClientsDocuments model.
 */
class ClientsDocumentsController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }
//...
public function actionCreate($id)
    {
        $model = new ClientsDocuments();
        $model->ClientId = $id;

        if ($model->load(Yii::$app->request->post())) {
            // return $this->redirect(['view', 'id' => $model->DocumentId]);.
            $UploadFile = \yii\web\UploadedFile::getInstance($model, 'UploadFile');
            if (!is_null($UploadFile)) {
                \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                return json_encode(['UploadFile' => $UploadFile->name]);
            } else {
                \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                return json_encode(['UploadFile' => 'NULL what the ...?']);  // *********** THIS IS ALWAYS THE CASE, it never get a file to work with??????
            }
            // ...
        }

        return $this->renderAjax('create', [
            'model' => $model,
        ]);
    }

No matter what I try, $UploadFile always seems to be null?

I was wondering if it could be related to my form’s JS

$('form#{$model->formName()}').on('beforeSubmit', function(e){
    $("#loading").show();

    var \$form = $(this);
    $.post(
        \$form.attr("action"), //serialize Yii2 form 
        \$form.serialize()
    )
    .done(function(result){
        result = JSON.parse(result); 
        console.log(result); 
    })
    .fail(
        function(xhr, status, error){
            var msg = "<span class=\"glyphicon glyphicon-remove\"></span><b>Javascript Error::Form/beforeSubmit()</b><br>"+xhr.responseText;
            var sysMsg = '<div id="w0-error-0" class="alert-danger alert fade in">'
                        + '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'
                        + '<span class="glyphicon glyphicon-warning-sign"></span> '+msg+'</div>';
            $("#modal-system-messages").html(sysMsg).stop().fadeIn().animate({opacity: 1.0}, 4000);
            $("#loading").fadeOut("slow");
        }
    );

    return false;
});

Thank you for your help in advance!

Hi, maybe you should modify this code

$model-> UploadFile = \yii\web\UploadedFile::getInstance($model, ‘UploadFile’);
if (!empty ($model-> UploadFile)) {