【问题标题】:Yii form with one upload field带有一个上传字段的 Yii 表单
【发布时间】:2013-06-15 19:10:20
【问题描述】:

我有一个只有一个字段的表单。

<?php echo $form->fileFieldRow($model,'img',array('rows'=>6, 'cols'=>50)); ?>

在我的模型中,我设置了 img 是必需的

array('img', 'required'),

并且我添加了一些文件验证规则

array('img', 'file', 'types'=>'jpg, gif, png' , 'maxFiles'=>'1'),           

选择图像并按提交后。我收到 'img' 是必需的错误。 这是因为 img 不是在 Post 中设置的,而是在 Files 中设置的。所以它没有看到 img 已设置。

有没有一种好方法可以让表单中只允许一个图片上传字段

【问题讨论】:

    标签: yii


    【解决方案1】:

    在你的表单中试试这个

    <?php $form=$this->beginWidget('CActiveForm', array(
        'id'=>'imageGallery-form',
        'action'=>Yii::app()->createAbsoluteUrl('/Controller/action'),
        'enableClientValidation'=>true,
        'clientOptions'=>array(
        'validateOnSubmit'=>true,
            ),
        'htmlOptions'=>array('enctype'=>'multipart/form-data'),// This is required for file upload
        )); ?>
    
    <div class="row">
            <span class="span-4">Uplaod images:</span>
            <?php echo $form->fileField($model,'Img',array('id'=>'file')); ?>
         ?>
    </div>
    

    添加一些脚本来验证文件字段

    <script type="text/javascript">
    $('#imageGallery-form').live("submit", function(event){
        var success = true;
        $form = $(this);
         if(/.*\.(gif)|(jpeg)|(jpg)|(doc)$/.test($("#file").val().toLowerCase())){
             $("#fname").removeClass("error");
        }else{
            $("#error_ul").append("<li>Please Choose Gif or Jpg Images Only.!!</li>");
            $(".errorSummary").show();
            $("#fname").addClass("error");
            success = false;
        }
    
    }); 
    </script>
    

    并在 Controller 端访问如图所示的图像

    public function actionGetImage(){
        if(isset($_POST['imageUploadBtn'])){
            $Img=CUploadedFile::getInstance($model, 'Img');
        }
    

    }

    【讨论】:

    • 由于某种原因,jquery .live("submit") 似乎没有被触发。该表单也不会提交,因为它验证为 img not set。但它确实删除了错误消息。如果我将 action 放入表单中,表单会以一种相当奇怪的方式提交。首先它会快速显示错误消息,然后转到创建操作。我通常不设置动作,这意味着它只是转到当前控制器。我可以根据需要删除 img,但随后表单提交时甚至根本没有选择图像。
    • 注释这两行并检查 array('img', 'required'), array('img', 'file', 'types'=>'jpg, gif, png' , 'maxFiles '=>'1'),
    • 我现在删除了验证。是否有另一种方法来触发 jquery live 函数,因为现在它在没有任何验证的情况下提交。非常感谢。
    • 你是否添加了我帖子中提供的脚本,它应该在提交之前对其进行验证
    • 是的,如下:$(function() { $('#imageGallery-form').live("submit", function(event){ ... }); }); 如果我将 live 更改为 bind,它似乎确实有效。但不确定这是正确的方法
    猜你喜欢
    • 2014-04-27
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 2011-09-14
    • 2011-07-02
    • 2020-03-30
    • 2013-01-12
    • 1970-01-01
    相关资源
    最近更新 更多