yii:如何在运行submitbutton之前运行一个函数

时间:2014-06-14 10:55:17

标签: php yii

我需要在yii 1.1.X

中运行提交按钮之前运行一个函数

我的函数是getcode(),格式为

这是我在 _form.php

中的代码

我希望从此函数中设置(group textfiled)

<?php
/* @var $this TextController */
/* @var $model Text */
/* @var $form CActiveForm */

?>

<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'text-form',
    'enableAjaxValidation'=>TRUE,
     'focus'=>array($model,'group'),
  //   'clientOptions'=>array(
     //           'validateOnChange'=>true,  // the default. validate when input changes
     //           'validateOnType'=>'true',    // validate with EVERY keystroke, hooray!
      //          'validationDelay'=>10,     // not related to this post--but cool!
      //                                // default delay is 200 ms
    //    ),
)); ?>

    <p class="note">Fields with <span class="required">*</span> are required.</p>

    <?php echo $form->errorSummary($model); ?>

    <div class="row">
        <?php echo $form->labelEx($model,'subject'); ?>
        <?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>80)); ?>
        <?php echo $form->error($model,'subject'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'matn'); ?>
        <?php echo $form->textField($model,'matn',array('size'=>60,'maxlength'=>255)); ?>
        <?php echo $form->error($model,'matn'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'group'); ?>
        <?php echo $form->textField($model,'group',array('value'=>$groupNumber , 'size'=>20,'maxlength'=>20)); ?>
        <?php echo $form->error($model,'group'); ?>

    </div>
<?php $userX=yii::app()->session['idX']; ?>

    <div class="row">
        <?php // echo $form->labelEx($model,'user_id'); ?>
        <?php echo $form->textField($model,'user_id',array ('value'=>$userX,'type'=>"hidden")); ?>
        <?php // echo $form->error($model,'user_id'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'Privacy'); ?>
        <?php echo $form->dropDownList($model,'Privacy',  array('1'=>'Public','2'=>'Only me')); ?>
        <?php echo $form->error($model,'Privacy'); ?>
    </div>

    <div class="row buttons">

        <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save' ); ?>
    </div>

<?php $this->endWidget(); ?>

</div><!-- form -->

<?php
function getcode()
{
    $groupNumber =Text::model()->maxIdNote();
}

如何在保存表单之前运行此函数。

这是我的文字模型

<?php

/**
 * This is the model class for table "text".
 *
 * The followings are the available columns in table 'text':
 * @property integer $id
 * @property string $subject
 * @property string $matn
 * @property string $group
 * @property integer $user_id
 * @property integer $Privacy
 *
 * The followings are the available model relations:
 * @property Users $user
 */
class Text extends CActiveRecord
{

    public $newId=0 ;
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'text';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('subject, user_id, Privacy ,group', 'required'),
            array('user_id, Privacy', 'numerical', 'integerOnly'=>true),
            array('subject', 'length', 'max'=>80),
            array('matn', 'length', 'max'=>255),
            array('group', 'length', 'max'=>20 , 'min'=>2),
                   array('group', 'comp_group'),

            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id, subject, matn, group, user_id, Privacy', 'safe', 'on'=>'search'),
        );
    }

            public function getidX()

      {

            $user= Yii::app()->db->createCommand();
   //     SELECT users.username from users INNER JOIN text  on text.user_id=users.id
         //   SELECT users.username FROM users,  text  WHERE users.id=text.user_id;
     $user = Yii::app()->db->createCommand()
    ->select('users.id')
    ->from('users')
    ->where('users.id=:username' , array(':username'=>1))
//    ->where('id=:id', array(':id'=>$id))
    ->queryRow();
Yii::app()->session['idX']=$user;
    return $user;
      }






    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'user' => array(self::BELONGS_TO, 'Users', 'user_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'subject' => 'Subject',
            'matn' => 'Matn',
            'group' => 'Group',
            'user_id' => 'User',
            'Privacy' => 'Privacy',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('subject',$this->subject,true);
        $criteria->compare('matn',$this->matn,true);
        $criteria->compare('group',$this->group,true);
        $criteria->compare('user_id',$this->user_id);
        $criteria->compare('Privacy',$this->Privacy);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Text the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

       public function comp_group($attributes , $params)
         {

            $sqlname='SHOW COLUMNS FROM `group`';
            $gpnamet = Yii::app()->db->createCommand($sqlname);
            $gpall =$gpnamet->queryAll();
            $sqlnumber="SELECT COUNT(*)
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE  table_name = 'group' ";
            $sqlnumberquery= Yii::app()->db->createCommand($sqlnumber);
            $sqlnumberall=$sqlnumberquery->queryAll();
            $numberColumns=( $sqlnumberall[0]['COUNT(*)']);

            for ($t=1 ; $t<$numberColumns ;$t++)
                {
                    $columnsArray[]=($gpall[$t]['Field']);

                }

    $test_status=FALSE;
    $numberint=0;

         $masterCommand = Yii::app()->db->createCommand();
                  $gname=$this->group;
              foreach ($columnsArray as $u)
              {
                   //  اگه گروه وارد شده موجود بود
                if ($this->group == $u )
                    {
                 $this->clearErrors('group');
             //    $this->addError('group' ," $gname already registered");
                 $masterCommand->reset();
                 $masterCommand->insert('group',
                          array
                                  (
                                       $this->group=>'1',
                                   ));
                  $masterCommand->reset();
                  $this->newId=$masterCommand->select('max(id)')->from('group')->queryAll();
                  $this->newId=$this->newId[0]['max(id)'];
                  $test_status=TRUE;

                  break;

                   }

          }
           // اگه گروه وارد شده موجود نبود و نیاز داشت به ستون ها اضافه شود
         foreach ($columnsArray as $u)   
         {
            if($test_status==FALSE && $this->group != $u)
                    {

                        $this->clearErrors('group');
                   //      $this->addError('group' ," $gname not registered");



                           if($numberint==0)
                           {
                            $masterCommand->reset();
                          $masterCommand->addColumn('group' , $gname , 'int(1)'); 
                         $masterCommand->reset();
                          $masterCommand->insert('group', array(
                                          $this->group=>'1',
                               ));
                            $masterCommand->reset();
                             $this->newId = $masterCommand->select('max(id)')->from('group')->queryAll();
                             $this->newId= $this->newId[0]['max(id)'];

                              $numberint++;

                               }
                          }
                   }
             }







      public function  maxIdNote()
      {
         return $this->newId;
      }
}

2 个答案:

答案 0 :(得分:1)

试试这个(请替换所需的值,尤其是ACTION_NAME) -

更改视图文件 -

<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save' ); ?>

<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save', array('id' => 'text_form_submit') ); ?>

将此内容写在视图文件的末尾 -

<script>
    $(document).ready(function() {
        $('#text_form_submit').click(function(ev) {
            ev.preventDefault();

            $.ajax({
                type: 'GET',
                dataType: 'JSON',
                url: '<?php echo Yii::app()->createUrl("text/ACTION_NAME"); ?>',
                success:function(data){
                    if(data !==  null) {
                        $('#Text_group').val(data);
                        $('#text-form').submit();
                    }
                },
                error: function() {
                    alert("Error occured!!!.");
                },
            });

            return false;
        });
    });
</script>

在TextController中 -

创建一个新动作(与ACTION_NAME替代的内容相同) -

public function actionACTION_NAME() {
    $groupNumber = Text::model()->maxIdNote();
    echo json_encode($groupNumber);
    exit();
}

答案 1 :(得分:1)

这是我的新代码

_form.php这个

<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'text-form',

    // See class documentation of CActiveForm for details on this.
    'enableAjaxValidation'=>TRUE,
   // 'action'=>$this->createUrl('TextController/performAjaxValidation'),
     'focus'=>array($model,'group'),
  //   'clientOptions'=>array(
     //           'validateOnChange'=>true,  // the default. validate when input changes
     //           'validateOnType'=>'true',    // validate with EVERY keystroke, hooray!
      //          'validationDelay'=>10,     // not related to this post--but cool!
      //                                // default delay is 200 ms
    //    ),
)); ?>

    <p class="note">Fields with <span class="required">*</span> are required.</p>

    <?php echo $form->errorSummary($model); ?>

    <div class="row">
        <?php echo $form->labelEx($model,'subject'); ?>
        <?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>80)); ?>
        <?php echo $form->error($model,'subject'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'matn'); ?>
        <?php echo $form->textField($model,'matn',array('size'=>60,'maxlength'=>255)); ?>
        <?php echo $form->error($model,'matn'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'group'); ?>
        <?php echo $form->textField($model,'group',array('size'=>20,'maxlength'=>20,'value'=>$test)); ?>
        <?php echo $form->error($model,'group'); ?>
    </div>
<?php $userX=yii::app()->session['idX']; ?>

    <div class="row">
        <?php // echo $form->labelEx($model,'user_id'); ?>
        <?php echo $form->textField($model,'user_id',array ('value'=>$userX,'type'=>"hidden")); ?>
        <?php // echo $form->error($model,'user_id'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'Privacy'); ?>
        <?php echo $form->dropDownList($model,'Privacy',  array('1'=>'Public','2'=>'Only me')); ?>
        <?php echo $form->error($model,'Privacy'); ?>
    </div>

    <div class="row buttons">
      <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save', array('id' => 'text_form_submit') ); ?>

    </div>

<?php $this->endWidget(); ?>

</div><!-- form -->

<script>
    $(document).ready(function() {
        $('#text_form_submit').click(function(ev) {
            ev.preventDefault();

            $.ajax({
                type: 'GET',
                dataType: 'JSON',
                url: '<?php echo Yii::app()->createUrl("text/ACTION_NAME"); ?>',
                success:function(data){
                //    if(data !==  null)
                    {
                   //     $('#Text_group').val(data);
                    //    $('#text-form').submit();
                         alert("not Error occured!!!.");
                    }
                },
                error: function() {
                    alert("Error occured!!!.");
                },
            });

            return false;
        });
    });
</script>

这是我的textController

<?php

class TextController extends Controller
{


    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout='//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters()
    {

        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('index','view'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('create','update'),
                'users'=>array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions'=>array('admin','delete'),
                'users'=>array('admin'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
              $model=$this->loadModel($id);

    //check user_id
    if ($model->user_id !== Yii::app()->user->id)
    {
        echo "YOU SHALL NOT PASS !";
        Yii::app()->end();
    }

        $this->render('view',array(
            'model'=>$this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $model=new Text;

        // Uncomment the following line if AJAX validation is needed
         $this->performAjaxValidation($model);

        if(isset($_POST['Text']))
        {
            $model->attributes=$_POST['Text'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('create',array(
            'model'=>$model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
          $model=$this->loadModel($id);

    //check user_id
    if ($model->user_id !== Yii::app()->user->id)
    {
        echo "YOU SHALL NOT PASS !";
        Yii::app()->end();
    }

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Text']))
    {
        $model->attributes=$_POST['Text'];
        if($model->save())
            $this->redirect(array('view','id'=>$model->id));
    }

    $this->render('update',array(
        'model'=>$model,
    ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if(!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
          // group model
           //   $dataProvidergroup=new CActiveDataProvider('group',array(
        //    'criteria' => array(
           // 'condition' => 'name=:user_id',
          //  'params' => array(':user_id' => Yii::app()->User->id),)
                //  ));



            //note of user
            $dataProviderself=new CActiveDataProvider('Text',array(
            'criteria' => array(
            'condition' => 'user_id=:user_id',
            'params' => array(':user_id' => Yii::app()->User->id),)));


            // public notes of users
            $dataProviderpublic = new CActiveDataProvider('Text',array(
            'criteria' => array(
            'condition' => 'privacy=:privacy',
            'params' => array(':privacy' => 1),)));



            $this->render('index',array(
        'dataProviderpublic'=>$dataProviderpublic ,
        'dataProviderself'=>$dataProviderself ,

    ));




//      $dataProvider=new CActiveDataProvider('Text');
//      $this->render('index',array(
//          'dataProvider'=>$dataProvider,
//      ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $model=new Text('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Text']))
            $model->attributes=$_GET['Text'];

        $this->render('admin',array(
            'model'=>$model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return Text the loaded model
     * @throws CHttpException
     */
       public $s=0;
    public function loadModel($id)
    {
        $model=Text::model()->findByPk($id);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param Text $model the model to be validated
     */
    protected function performAjaxValidation($model)
    {

          if(isset($_POST['ajax']) && $_POST['ajax']==='text-form')
        {
            echo CActiveForm::validate($model);

            Yii::app()->end();
        }
    }

      public function actionACTION_NAME()
              {
              $groupNumber = 26;
                      //Text::model()->maxIdNote();
              echo json_encode($groupNumber);
              exit();
}
}