【问题标题】:yii active form validation on modal dialogyii 模态对话框上的活动表单验证
【发布时间】:2014-11-13 11:32:23
【问题描述】:

我正在尝试在模式对话框中验证 CActiveForm。我使用引导程序。 问题是模态对话框。当我在加载主 html 页面 JavaScriopt 验证工作期间读取表单内容时,但是当我在单击按钮时加载内容时,验证脚本消失了。 这是调用页面的视图

<?php
/* @var $this SiteController */

$this->pageTitle=Yii::app()->name . ' - Все магазины';
$this->breadcrumbs=array(
    'Shops',
);

$jsCreate = "$(\".createShop\").click(function(){
    var target = $(this).attr('data-target');
    var url = '?r=site/editShop';
    $(target).find(\".modal-dialog\").load(url);
});";
Yii::app()->getClientScript()->registerScript('create-shop-script',$jsCreate,CClientScript::POS_READY);

$jsEdit = "$(\".editShop\").click(function(){
    var target = $(this).attr('data-target');
    var url = $(this).attr('href');
    $(target).find(\".modal-dialog\").load(url);
});";
Yii::app()->getClientScript()->registerScript('edit-shop-script',$jsEdit,CClientScript::POS_READY);


$jsDelete = "$(\".deleteShop\").click(function(){
    var target = $(this).attr('data-target');
    var url = $(this).attr('href');
    $(target).find(\".modal-dialog\").load(url);
});";
Yii::app()->getClientScript()->registerScript('delete-shop-script',$jsDelete,CClientScript::POS_READY);
?>

<h2>Все объекты</h2>
 <!-- I created separate dialog for shop and warning because on open it shows the previous content while forming the new one 
      and I don't want to show shop elements on warning and vise versa -->
<!-- modal dialog for shop -->
<div id="shopModal" class="modal fade" aria-hidden="true" style="display: none;">
    <div class="modal-dialog">

    </div>
</div>

<!-- modal warning dialog -->
<div id="warningModal" class="modal fade" aria-hidden="true" style="display: none;">
    <div class="modal-dialog">

    </div>
</div>

<table class="table table-hover">
    <thead>
        <tr>
            <th>Название <span class="hidden-xs">объекта</span></th>
            <th><span class="glyphicon glyphicon-ok visible-xs"  data-toggle="tooltip" title="Статус активности"></span><span class="hidden-xs">Статус</span></th>
        </tr>
    </thead>
    <?php foreach($shops as $shop) :?>
    <?php $disabled = ($shop->active) ?'' :'gray'?>
    <tr>            
                <td><span class="<?php echo $disabled; ?>"><?php echo $shop->name; ?></span></td>
                <td>
                    <?php echo ($shop->active) ?"<span data-toggle='tooltip' title='Активен' class='glyphicon glyphicon-eye-open'></span>" :"<span data-toggle='tooltip' title='Неактивен' class='glyphicon glyphicon-eye-close'></span>" ?>
                    &nbsp; <a data-toggle='modal' data-target='#shopModal' class="editShop" href="?r=site/editShop&amp;id=<?php echo $shop->id; ?>"><span data-toggle='tooltip' title='Редактировать объект' class="glyphicon glyphicon-edit"></span></a>
                    &nbsp; <a data-toggle='modal' data-target='#warningModal' class="deleteShop" href="?r=site/deleteShop&amp;id=<?php echo $shop->id; ?>"><span data-toggle='tooltip' title='Удалить объект' class="glyphicon glyphicon-remove-circle"></span></a>
                </td>
    </tr>
    <?php endforeach; ?>
</table>
<button style='float:right;' data-toggle='modal' data-target='#shopModal' class="createShop btn btn-primary"><span data-toggle="tooltip" title="Добавить объект"><span class="glyphicon glyphicon-plus"></span> <span class="hidden-xs">Добавить объект</span></span></button>

这是显示在模态对话框中的表单视图

<?php
/* 
   @var $this SiteController 
   @var $form CActiveForm */
?>
<?php
$form=$this->beginWidget('CActiveForm', array(
        'id'=>'shop-form',
        'enableClientValidation'=>true,
        'clientOptions'=>array(
                'validateOnSubmit'=>true,
        ),
        'htmlOptions'=> array('class'=>'bottom0',),
        'action'=>"$url&id={$model->id}",
));?>   
  <div class="modal-content panel-primary">
      <div class="modal-header panel-heading">
          <button type="button" class="close panel-title" data-dismiss="modal" aria-hidden="true"><span data-container="body" data-toggle="tooltip" title="Закрыть">×</span></button>  
        <h4 class="modal-title panel-title"><?php echo $title;?></h4>
      </div> <!-- end modal-header -->

      <div class="modal-body">
        <div class="form-group">              
              <?php echo $form->textField($model,'name',array('data-toggle'=>'tooltip', 'title'=>'Название', 'class'=>'form-control', 'placeholder'=>'Название', 'maxlength'=>'50')); ?>
              <?php echo $form->error($model,'name'); ?>
        </div>
          <div class="form-group">
              <label data-toggle="tooltip" title="Статус активноси">
                  <?php echo $form->checkBox($model,'active') .' '. $form->label($model,'active') . $form->error($model,'active'); ?>
              </label>
          </div>
      </div> <!-- end modal-body -->


      <div class="modal-footer">
          <!-- Save button -->
          <button type="submit" class="btn btn-primary"><span data-toggle="tooltip" title="Сохранить"><span class="glyphicon glyphicon-ok"></span> <span class="hidden-xs">Сохранить</span></span></button>
          <!-- Cancel button -->
          <button type="button" class="btn btn-default" data-dismiss="modal"><span data-toggle="tooltip" title="Отменить"><span class="glyphicon glyphicon-remove"></span> <span class="hidden-xs">Отменить</span></span></button>
     </div> <!-- end modal-footer -->
  </div>
 <?php $this->endWidget(); ?>

这是我的商店模型

<?php

/**
 * This is the model class for table "shops".
 *
 * The followings are the available columns in table 'shops':
 * @property integer $id
 * @property string $name
 * @property string $active
 */

class Shops extends CActiveRecord
{

public function tableName()
{
    return 'shops';
}

public function rules()
{
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        array('name', 'length', 'max'=>255),
        array('active', 'length', 'max'=>1),
        array('id, name, active', 'safe', 'on'=>'search'),
    );
}

public function relations()
{
    return array();
}

public function attributeLabels()
{
    return array(
        'id' => 'ID',
        'name' => 'Name',
        'active' => 'Active',
    );
}


public static function model($className=__CLASS__)
{
    return parent::model($className);
}
}

这是我处理商店创建/更新/删除的站点控制器

public function actionEditShop($id=null)
{
        if (!$this->checkAuthenticated()) return;


       if(isset($_POST['ajax']) && $_POST['ajax']==='shop-form')
        {
          echo CActiveForm::validate($model);
            Yii::app()->end();
        }
        $model = $this->loadShop($id);
        if(isset($_POST['Shops']))
        {   
            // create/update shop               
            $fields = $_POST['Shops'];
            $fields['id'] = $id;
            $model->attributes=$fields;

            if($model->save())
                    $this->redirect(array('shops'));
        } else {
            // open form to create/update                
            $this->renderPartial('classifier',array('model'=>$model, 'title'=>'Объект', 'url'=>'?r=site/editShop'), false, true);
        }
}

    public function actionDeleteShop($id, $confirmed=null)
{
        if (!$this->checkAuthenticated()) return;
        $model = $this->loadShop($id);
        if (isset($confirmed)){
    $model->delete();
    $this->redirect(array('shops'));
        } else {
            $this->renderPartial('warning',array('url'=>"?r=site/deleteShop&id=$id&confirmed=1",));
        }
}

    private function loadShop($id=null)
{
        if ($id){
    $model=Shops::model()->findByPk($id);
    if($model===null)
        throw new CHttpException(404,"Объект под номером $id не существует.");
        } else {
            $model = new Shops; // creates with active='1'
            $model->active = '1';
        }
        return $model;
}

【问题讨论】:

    标签: javascript twitter-bootstrap validation yii modal-dialog


    【解决方案1】:

    您需要使用renderPartial()processOutput 参数明确告诉您的控制器包含您的脚本。设置后,processOutput() 会被调用:

    render() 生成的输出进行后处理。该方法被调用 在 render()renderText() 的末尾。如果有注册 客户端脚本,此方法会将它们插入到输出中 合适的地方。如果有动态内容,它们也将是 插入。此方法还可以将持久页面状态保存在 页面中状态表单的隐藏字段。

    你也应该取消注释

    $this->performAjaxValidation($model);
    

    如果您使用processOutput,请查看Yii renderpartial (proccessoutput = true) Avoid Duplicate js request

    【讨论】:

    • 我改了,但没办法
    • 验证脚本现在出现在代码中了吗?
    • 对不起。有一个不正确的部分。现在我改变了所有的部分。请注意,在呈现页面后,表单正在模式对话框中加载,因此验证 javascript 不会出现在结果页面上。我将它与 Yii 登录对话框进行了比较。将表单移动到模式对话框后,有几个验证脚本不存在
    • 这些缺失的脚本是你自己的还是默认的 Yii 脚本?
    猜你喜欢
    • 1970-01-01
    • 2019-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多