Yii:使用Ajax将模型中的变量返回到表单

时间:2014-06-11 04:37:23

标签: ajax yii

如何更改模型以便从ajax将模型中的varibale发送到我的表单? 我希望这可以发生在连接到我的表单的(公共函数comp_group)模型中。 我希望我的模型返回 $ maxId _form.php

这是我的_form.php

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

<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'text-form',
    // Please note: When you enable ajax validation, make sure the corresponding
    // controller action is handling ajax validation correctly.
    // There is a call to performAjaxValidation() commented in generated controller code.
    // See class documentation of CActiveForm for details on this.
    '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('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
$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']);

}
print_r($columnsArray);
//$masterCommand = Yii::app()->db->createCommand();

?>

这是我的模特:

/**
 * 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
{
    /**
     * @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']);
            }
//print_r($columnsArray);

          foreach ($columnsArray as $u)
          {
              $masterCommand = Yii::app()->db->createCommand();
              $gname=$this->group;



              if($this->group == $u)
              {
                 $this->addError('group' ," $gname already registered");
                 $masterCommand->reset();
                 $masterCommand->insert('group',
                          array
                              (
                  $this->group=>'1',
                                ));
                 $maxId = $masterCommand->select('max(id)')->from('group')->queryAll();
                 $maxId=   $maxId[0]['max(id)'];

                  break;
              }


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


                    }

          }
      }
}

0 个答案:

没有答案