yii2上传文件给出空白数组

时间:2018-08-23 05:33:36

标签: php file-upload yii2

在yii2中,使用UploadedFile的

采用空白数组。尝试

print_r($model->attachments);
exit();

然后采用空白数组。有什么建议么?仅文件上传有问题,请告诉我该怎么办?我尝试过getinstancebyname仍然无法正常工作。

public function actionOpentnew()
{
    $model = new Ticket;

    if(Yii::$app->request->isAjax && $model->load($_POST))
    {            
       $model->validate();
       if($model->hasErrors())
        {
            Yii::$app->response->format = 'json';
            return ActiveForm::validate($model);
        }
    }

    // if($model->load(Yii::$app->request->post()) && !isset($_POST['ajax']))
    // if($model->load(Yii::$app->request->post()) && $model->validate())   
    if($model->load(Yii::$app->request->post()) && $model->validate() && $_POST['buttonclick']==1 && !isset($_POST['ajax']))
    {        
        $model->attachments = UploadedFile::getInstances($model, 'attachments');

        print_r($model->attachments);
        exit();

        if(!empty($model->attachments))
        {
            if ($model->upload()) 
            {                   
                foreach ($model->attachments as $key => $value)
                {

                    $attachmenttxt.= $value->name."|";
                }
            }
        }

        $data = array();
        $data = $_POST['Ticket'];
        $data['action'] = 'OpenTicket';
        $data['clientid'] = \Yii::$app->user->identity->id;

        $TicketDetails = WHMCSAPI::callApi($data);

        Log::log(serialize($TicketDetails),'','Support ticket open',serialize($data));
        if(!empty($model->attachments))
        {
            $modelAttachment = new TicketAttachment;
            $modelAttachment->ticketid = $TicketDetails['id'];
            $modelAttachment->tid = $TicketDetails['tid'];                
            $modelAttachment->attachment = $attachmenttxt;
            $modelAttachment->Userid = \Yii::$app->user->identity->id;
            $modelAttachment->save();
        }

        if($TicketDetails['result']=='success')
        {                
            Yii::$app->session->setFlash('success', Yii::t('app', 'Ticket created Successfully!'));    
        }else{
           Yii::$app->session->setFlash('warning', Yii::t('app', 'Ticket not created! Something is Wrong'));     
        }
        return $this->redirect(['ticket/index']);
    }

    return $this->render('openticketdemo',['model'=>$model]);
}

1 个答案:

答案 0 :(得分:-1)

这是查看页面。

<?php
use yii\helpers\Html;
use yii\helpers\BaseHtml;
use yii\widgets\DetailView;
use yii\widgets\ActiveForm;
use app\models\Countries;
use app\models\Ticket;
use yii\helpers\Url;
?>

<div class="ibox-title"><h5><?=Yii::t('app', 'SUPPORT TICKETS') ?> <small><?=Yii::t('app', 'If you can\'t find a solution to your problems in our knowledgebase, you can submit a ticket by selecting the appropriate department below.') ?></small></h5></div>


<div class="ibox-content">   

   <div id="ticket_loader" >
   </div>
<?php $form = ActiveForm::begin(
            ['action' =>'',
            'options' => ['method'=>'post','class'=>'form-horizontal','id'=>'frm-introduction','enctype'=>'multipart/form-data'],
            'fieldConfig' => [
                'template' => "{label}<div class=\"col-md-4\">{input}\n{error}</div>",
                'labelOptions' => ['class' => 'col-lg-2 control-label'],
            ],
            'enableAjaxValidation'=>true,'enableClientValidation' => false,'validateOnSubmit'=>true]); ?>

            <?= $form->field($model, 'deptid')->dropDownList(Ticket::getSupportDepartment(),['prompt'=>'Select...']); ?>
                    <?= $form->field($model, 'subject'); ?>

                    <?= $form->field($model, 'priority')->dropDownList(Ticket::getPriority(),['prompt'=>'Select...']); ?>

                    <?= $form->field($model, 'serviceid')->dropDownList(Ticket::getRelatedServices(),['prompt'=>'Select...', 'onchange' => 'changeSubCategory(this);']); ?>

                    <?= $form->field($model, 'subcat_id')->dropDownList('', ['onchange' => 'checkSubCategory(this);']); ?>

                    <div id="other_description" class="hide">

                        <?= $form->field($model, 'description')->textArea(['rows'=>'4','cols'=>'6','placeholder'=>Yii::t('app', 'Description'), 'maxlength'=>"250"]); ?>
                    </div>
                    <?= $form->field($model, 'message')->textArea(['rows'=>'9','cols'=>'6']); ?>

                    <?= $form->field($model, 'attachments[]')->fileInput(['multiple' => true, 'accept' => 'image/*']); ?>

        <div class="form-group m-t-20">           
            <div class="pull-right">
                <input type="hidden" name="buttonclick" id="buttonclick" value="0">

             <?= Html::submitButton(Yii::t('app', 'Submit Ticket'), 
                    ['class'=>'btn btn-primary',
                    'onclick'=>'ticketData()']) ?>

                    <!-- <?php
                        app\vendor\demogorgorn\yii2ajax\AjaxSubmitButton::begin([
                            'label' => Yii::t('app','Submit Ticket'),
                            'id'=>'volume-button',
                            'ajaxOptions' => [
                                'type'=>'POST',
                                // 'dataType' => 'json',
                                // 'data'=>'js:$("#frm-introduction").serialize()',//this one
                                'url'=>new \yii\web\JsExpression('$(this).closest("form")[0].action'),

                                'beforeSend'=> new \yii\web\JsExpression('function() {
                                            $("#frm-introduction .help-block").html("");
                                            $("#frm-introduction div").removeClass("has-error");
                                            $("#ticket_loader").html("<div class=\"sk-spinner sk-spinner-three-bounce\"><div class=\"sk-bounce1\"></div><div class=\"sk-bounce2\"></div><div class=\"sk-bounce3\"></div></div>");
                                        }'),

                                'success' => new \yii\web\JsExpression('function(data){   

                                    $("#ticket_loader").html("");
                                      //console.log(response);  

                                    if(jQuery.type(data)=="object"){
                                        $.each(data, function( index, value ) {
                                        $("#frm-introduction #"+index).next().html(value);
                                        $("#frm-introduction #"+index).parent().parent().addClass("has-error");   

                                       });  
                                       }else{
                                            var obj = jQuery.parseJSON(data);
                                              if(obj.status=="success"){
                                             $("#frm-introduction").html("form submitted successfully.");
                                             $("#frm-introduction")[0].reset();
                                            }    
                                       } 

                                    }'),
                                    ],
                                    'options' => ['class' => 'btn btn-primary', 'type' => 'submit','onclick'=>'$("#buttonclick").val(1);'],
                                    ]);
                                app\vendor\demogorgorn\yii2ajax\AjaxSubmitButton::end();
                    ?> -->

                    <?= Html::a(Yii::t('app', 'Cancel'), Url::to(['/ticket/index']), ['class'=>'btn btn-link', 'data-toggle'=>'block', 'data-reset'=>'#w6', 'data-target'=>'dt-aboutme']) ?>
           <!--  <a class="btn btn-link" href="/ticket/index" data-toggle="block" data-reset="#w6"  data-target="dt-aboutme">Cancel</a> -->

        </div>
        </div>

<?php ActiveForm::end(); ?>
<div id="form3d"></div>
</div>

<script type="text/javascript">

    /*$("#frm-introduction").on("submit", function(){

       });
*/
    function changeSubCategory(obj)
    {
        console.log($(obj).val());
        var serviceid = $(obj).val();
        $.ajax({
                "type":"POST",
                "url":'/dynamic/get-ticket-sub-category',
                "data": 'serviceid='+serviceid+'&_csrf=<?php echo Yii::$app->request->csrfToken; ?>',
                "dataType": 'json',
                "beforeSend":function(){
                        $('#ticket-subcat_id').find("option:eq(0)").html("Please wait..");
                        $("#loader").html("<div class=\"sk-spinner sk-spinner-three-bounce\"><div class=\"sk-bounce1\"></div><div class=\"sk-bounce2\"></div><div class=\"sk-bounce3\"></div></div>");
                        },
                "success":function(response)
                {
                    if(response.tp == 1)
                    {
                        var option = $('<option />');
                        $('#ticket-subcat_id').html("");
                        //$('#ticket-subcat_id').append(option);
                        $.each(response['result'], function(key, val) {
                            var items = val.split('|');
                            var option = $('<option />');
                            if (items[1] == 'Select') {
                                option.attr('value', '').text(items[1]);
                            }
                            else
                                option.attr('value', val).text(items[1]);
                            $('#ticket-subcat_id').append(option);
                        });

                        var firstoptionitems = $('#ticket-subcat_id').find("option:eq(0)").val().split('|');
                        if (firstoptionitems[1] == 'Other')
                        {
                            $('#other_description').removeClass('hide');
                        }
                        else
                            $('#other_description').addClass('hide');
                    }
                    else{
                        console.log(response.msg);
                    }
                    $("#loader").html("");
                    //successMessage('Card set to Default');
                }
            }); 
    }

    function checkSubCategory(obj)
    {
        var category = $(obj).val();
        var items = category.split('|');

        if (items[1] == 'Other') {
            $('#other_description').removeClass('hide');
        }
        else
            $('#other_description').addClass('hide');
    }



    function ticketData()
    {
        //var url = "<?=Url::to(['view']) ?>?id="+id;

        $.ajax({
                "type":"POST",
                "url":url,
                "beforeSend":function(){                                            
                                            $("#ticket_loader").html("<div class=\"sk-spinner sk-spinner-three-bounce\"><div class=\"sk-bounce1\"></div><div class=\"sk-bounce2\"></div><div class=\"sk-bounce3\"></div></div>");
                                        },
                "success":function(response){   
                                                $("#ticket_loader").html("").html(response);
                                                //$("#productdetailsLabel").html($('#title').val());
                                            }
            }); 
    }

 </script>