【问题标题】:Yii dropDownList - where to do logic for selected itemYii dropDownList - 在哪里为选定项目执行逻辑
【发布时间】:2014-10-12 03:20:10
【问题描述】:

我正在尝试从 CActiveForm 的 dropDownList 中捕获选择的值,然后在提交后对其执行一些逻辑...然后运行查询。然后,基于此查询,我将更新 gridview。此表单在表中没有任何与其相关的属性,但它更多,因此我可以在一些逻辑后为我的 GridView 创建一个过滤器。

我将在哪里执行此逻辑?我是 php、yii 和 javascript 的新手,所以我会很感激至少能指出我正确的方向。我试图查看 yii 文档和书籍,但没有找到我需要的东西。我认为我错过了 php 和 web 开发中的一些关键内容,以至于被困在像下拉菜单这样微不足道的事情上。

这是我对 admin.php 的看法,然后通过 renderPartial 调用 advanced_search.php 表单

    <?php
/* @var $this UserController */
/* @var $model User */

$this->breadcrumbs=array(
    'Manage Users',
);

/*$this->menu=array(
    array('label'=>'List User', 'url'=>array('index')),
    array('label'=>'Create User', 'url'=>array('create')),
);
*/
Yii::app()->clientScript->registerScript('search', "
$('.asearch-button').click(function(){
    $('.asearch-form').toggle();
    $('.bsearch-form').toggle();
    return false;
});

$('.bsearch-button').click(function(){
    $('.bsearch-form').toggle();
    $('.asearch-form').toggle();
    return false;
});

$('.bsearch-form form').submit(function(){
    $('#user-grid').yiiGridView('update', {
        data: $(this).serialize()
    });
    return false;
});

$('.asearch-form form').submit(function(){
    $('#user-grid').yiiGridView('update', {
        data: $(this).serialize()
    });
    return false;
}); 
");
?>

<h2>Manage Users</h2>

<?php echo CHtml::link('Basic Search','#',array('class'=>'bsearch-button')); ?>
<br/>

<!-- basic search-form -->
<div class="bsearch-form" style="display:">
    <?php $this->renderPartial('search',array('model'=>$model)); ?>
</div>


<?php echo CHtml::link('Advanced Search','#',array('class'=>'asearch-button')); ?>

<!-- advanced search-form -->
<div class="asearch-form" style="display:none">
    <?php $this->renderPartial('advanced_search',array('model'=>$model)); ?>
</div>


<?php $this->widget('bootstrap.widgets.TbGridView', array(
    'type'=>'striped condensed hover',
    'id'=>'user-grid',
    'selectableRows'=>1,
    'selectionChanged'=>
        'function(id){ location.href = $.fn.yiiGridView.getSelection(id);}',
    'dataProvider'=>$model->search(),
    'filter'=>$model,
    'columns'=>array(
        'username',
        'email',
        'fname',
        'lname',
        array(
            'name'  => 'combineRoles',
            'value' => '($data->getCombineRoles())',
            'header'=> CHtml::encode($model->getAttributeLabel('combineRoles')),
            //'filter'=> CHtml::activeTextField($model, 'combineRoles'),
        ),
    )));
?>

我的高级搜索.php

<?php
/* @var $this UserController */
/* @var $model User */
/* @var $form CActiveForm */
?>

<div class="wide form">
    <?php $form = $this->beginWidget('CActiveForm', array(
        'action' => Yii::app()->createUrl($this->route),
        'method' => 'get',
    )); ?>

        <?php

            $dataRole = array('Project Mentor', 'Personal Mentor', 'Domain Mentor', 'Mentee');
            $dataRoleVal = array(0,1,2,3);
            echo $form->dropDownList($model, 'firstField', array_combine($dataRoleVal, $dataRole),
                array('style' => ''));

            echo $form->dropDownList($model, 'criteria', array('Exactly', 'Greater Than',
                    'Less Than'), array('style' => ''));

            echo $form->textField($model, 'quantity', array('hint'=>'', 'style' => ''));

            $data = array('Enabled', 'Disabled');
            $data1 = array(0,1);
            echo $form->dropDownList($model, 'disable', array_combine($data1, $data), array('style' => ''));

        ?>

        <?php echo CHtml::submitButton('Search', array("class" => "btn btn-primary")); ?>

    <?php $this->endWidget(); ?>
    <!-- search-form -->
</div>

我的 UserController.php

public function actionAdmin()
{

    echo("<script>console.log('actionAdmin');</script>");


    $model=new User('search');
    $model->unsetAttributes();  // clear any default values
    if(isset($_GET['User'])){
        $model->attributes=$_GET['User'];

    }

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

更新:这里要求的是我的模型 User.php

    <?php

/**
 * This is the model class for table "user".
 *
 * The followings are the available columns in table 'user':
 * @property string $id
 * @property string $username
 * @property string $password
 * @property string $email
 * @property string $fname
 * @property string $mname
 * @property string $lname
 * @property string $pic_url
 * @property integer $activated
 * @property string $activation_chain
 * @property integer $disable
 * @property string $biography
 * @property string $linkedin_id
 * @property string $fiucs_id
 * @property string $google_id
 * @property integer $isAdmin
 * @property integer $isProMentor
 * @property integer $isPerMentor
 * @property integer $isDomMentor
 * @property integer $isStudent
 * @property integer $isMentee
 * @property integer $isJudge
 * @property integer $isEmployer
 *
 * The followings are the available model relations:
 * @property Administrator $administrator
 * @property DomainMentor $domainMentor
 * @property Mentee $mentee
 * @property Message[] $messages
 * @property Message[] $messages1
 * @property PersonalMentor $personalMentor
 * @property ProjectMentor $projectMentor
 * @property Ticket[] $tickets
 * @property Ticket[] $tickets1
 * @property Domain[] $domains
 */
class User extends CActiveRecord
{
    public $password2;
    public $vjf_role;
    public $men_role;
    public $rmj_role;
    /* advanced search variables */
    public $firstField;
    public $quantity;
    public $criteria;
    /*assign variables */
    public $userDomain;
    public $userId;
    /*temporary variables currently not stored in db*/
    public $employer;
    public $position;
    public $start_year;
    public $degree;
    public $field_of_study;
    public $school;
    public $graduation_year;
    public $combineRoles;
    /*Change the value when the system is deploy */
    public static $admin = 5;
    /* The most expert in the Domain */
    public static $condition = 8;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return User the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'user';
    }

    /**
     * @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('username, password, password2, email, fname, lname', 'required'),
            array('activated, disable, isAdmin, isProMentor, isPerMentor, isDomMentor, isStudent, isMentee, isJudge, isEmployer', 'numerical', 'integerOnly' => true),
            array('username, fname, mname, activation_chain, linkedin_id, fiucs_id, google_id', 'length', 'max' => 45),
            array('password, email, pic_url', 'length', 'max' => 255),
            array('lname', 'length', 'max' => 100),
            array('biography', 'length', 'max' => 500),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, username, password, email, fname, mname, lname, pic_url, activated, activation_chain, disable, biography, linkedin_id, fiucs_id, google_id, isAdmin, isProMentor, isPerMentor, isDomMentor, isStudent, isMentee, isJudge, isEmployer', 'safe', 'on' => 'search'),
        );
    }


    public function validatePassword($password)
    {
        $hasher = new PasswordHash(8, false);
        return $hasher->CheckPassword($password, $this->password);
    }

    /**
     * @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(
            'administrator' => array(self::HAS_ONE, 'Administrator', 'user_id'),
            'domainMentor' => array(self::HAS_ONE, 'DomainMentor', 'user_id'),
            'mentee' => array(self::HAS_ONE, 'Mentee', 'user_id'),
            'messages' => array(self::HAS_MANY, 'Message', 'receiver'),
            'messages1' => array(self::HAS_MANY, 'Message', 'sender'),
            'personalMentor' => array(self::HAS_ONE, 'PersonalMentor', 'user_id'),
            'projectMentor' => array(self::HAS_ONE, 'ProjectMentor', 'user_id'),
            'tickets' => array(self::HAS_MANY, 'Ticket', 'assign_user_id'),
            'tickets1' => array(self::HAS_MANY, 'Ticket', 'creator_user_id'),
            'domains' => array(self::MANY_MANY, 'Domain', 'user_domain(user_id, domain_id)'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'User ID',
            'username' => 'User Name',
            'password' => 'Password',
            'password2' => 'Re-type Password',
            'email' => 'e-mail',
            'fname' => 'First Name',
            'mname' => 'Middle Name',
            'lname' => 'Last Name',
            'pic_url' => 'Pic Url',
            'activated' => 'Activated',
            'activation_chain' => 'Activation Chain',
            'disable' => 'Disabled',
            'biography' => 'Biography',
            'linkedin_id' => 'Linkedin',
            'fiucs_id' => 'Fiucs',
            'google_id' => 'Google',
            'isAdmin' => 'Administrator',
            'isProMentor' => 'Project Mentor',
            'isPerMentor' => 'Personal Mentor',
            'isDomMentor' => 'Domain Mentor',
            'isStudent' => 'Student',
            'isMentee' => 'Mentee',
            'isJudge' => 'Judge',
            'isEmployer' => 'Employer',
            'vjf_role' => 'Virtual Job Fair Roles:',
            'men_role' => 'Mentoring Platform Roles:',
            'rmj_role' => 'Remote Mobil Judge Roles:',
            'employer' => 'Current Employer',
            'position' => 'Position',
            'start_year' => 'Start Year',
            'degree' => 'Highest Degree',
            'field_of_study' => 'Field of Study',
            'school' => 'University',
            'graduation_year' => 'Graduation Year',
            'rmj_role' => 'Remote Mobil Judge Roles:',
            'firstField' => 'Type: ',
            'criteria' => 'Assigned to: ',
            'quantity' => 'projects, mentors, or mentees',
            'combineRoles' => 'Roles',

        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.


        if ($this->firstField === 0) {
            $this->isProMentor = 1;
        } else if ($this->firstField === 1) {
            $this->isPerMentor = 1;
        } else if ($this->firstField === 2) {
            $this->isDomMentor = 1;
        } else if ($this->firstField === 3) {
            $this->isMentee = 1;
        }

        $criteria = new CDbCriteria;


        //$criteria->compare('id', $this->id, true);
        $criteria->compare('username', $this->username, true);
        //$criteria->compare('password',$this->password,true);
        $criteria->compare('email', $this->email, true);
        $criteria->compare('fname', $this->fname, true);
        //$criteria->compare('mname', $this->mname, true);
        $criteria->compare('lname', $this->lname, true);
        //$criteria->compare('pic_url',$this->pic_url,true);
        $criteria->compare('activated', $this->activated);
        //$criteria->compare('activation_chain',$this->activation_chain,true);
        $criteria->compare('disable', $this->disable);
        //$criteria->compare('biography',$this->biography,true);
        //$criteria->compare('linkedin_id',$this->linkedin_id,true);
        //$criteria->compare('fiucs_id',$this->fiucs_id,true);
        //$criteria->compare('google_id',$this->google_id,true);
        //$criteria->compare('isAdmin', $this->isAdmin);
        $criteria->compare('isProMentor', $this->isProMentor);
        $criteria->compare('isPerMentor', $this->isPerMentor);
        $criteria->compare('isDomMentor', $this->isDomMentor);
        $criteria->compare('isStudent', $this->isStudent);
        $criteria->compare('isMentee', $this->isMentee);
        //$criteria->compare('isJudge', $this->isJudge);
        //$criteria->compare('isEmployer', $this->isEmployer);

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

    public function getCombineRoles(){
        $st = '';

        if ($this->isProMentor)
            $st .= 'Project ';
        if ($this->isPerMentor)
            $st .= 'Personal ';
        if ($this->isDomMentor)
            $st .= 'Domain ';
        if ($this->isMentee)
            $st .= 'Mentee';

        return $st;
    }

    /* retrieve all user ids in the system */
    public static function getAllUserId()
    {
        $userid = User::model()->findBySql("SELECT id from user, user_domain WHERE  ");
        return $userid;
    }


    public static function getCurrentUser()
    {
        $username = Yii::app()->user->name;
        $user = User::model()->find("username=:username", array(':username' => $username));
        return $user;
    }


    public static function getCurrentUserId()
    {
        $username = Yii::app()->user->name;
    $user = User::model()->find("username=:username", array(':username' => $username));
    if ($user == null) { Yii::app()->getController()->redirect('/coplat/index.php/site/login');  }
        return $user->id;
    }


    public static function getUser($userid)
    {
        $user = User::model()->findByPk($userid);
        return $user;
    }

    public static function getUserName($userid)
    {
        $user = User::model()->findByPk($userid);
        return $user->username;
    }

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

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

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

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

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

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

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

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

    public static function isCurrentUserAdmin()
    {
        $username = Yii::app()->user->name;
        $user = User::model()->find("username=:username", array(':username' => $username));
        if ($user == null)
            return false;
        return $user->isAdmin;
    }

    public static function isCurrentUserMentee()
    {
        $username = Yii::app()->user->name;
        $user = User::model()->find("username=:username", array(':username' => $username));
        if ($user == null)
            return false;
        return $user->isMentee;
    }

    public static function isCurrentUserProMentor()
    {
        $username = Yii::app()->user->name;
        $user = User::model()->find("username=:username", array(':username' => $username));
        if ($user == null)
            return false;
        return $user->isProMentor;
    }

    public static function isCurrentUserDomMentor()
    {
        $username = Yii::app()->user->name;
        $user = User::model()->find("username=:username", array(':username' => $username));
        if ($user == null)
            return false;
        return $user->isDomMentor;
    }

    public static function isCurrentUserPerMentor()
    {
        $username = Yii::app()->user->name;
        $user = User::model()->find("username=:username", array(':username' => $username));
        if ($user == null)
            return false;
        return $user->isPerMentor;
    }

    public static function isCurrentUserJudge()
    {
        $username = Yii::app()->user->name;
        $user = User::model()->find("username=:username", array(':username' => $username));
        if ($user == null)
            return false;
        return $user->isJudge;
    }

    public static function isCurrentUserEmployer()
    {
        $username = Yii::app()->user->name;
        $user = User::model()->find("username=:username", array(':username' => $username));
        if ($user == null)
            return false;
        return $user->isEmployer;
    }

    public static function isCurrentUserStudent()
    {
        $username = Yii::app()->user->name;
        $user = User::model()->find("username=:username", array(':username' => $username));
        if ($user == null)
            return false;
        return $user->isStudent;
    }

【问题讨论】:

  • 粘贴你的模型文件(protected/models/User.php)代码public function search(){}
  • @Athipatla 感谢您的浏览。我更新了帖子以显示搜索功能。

标签: php yii drop-down-menu filter selected


【解决方案1】:

好的,我不知道你在尝试什么样的逻辑。我猜您想根据 advanced_search.php 中给出的搜索条件列出数据。您需要在 Search 函数中编写结果逻辑。

如果您无法理解,请告诉我。还激活、禁用、isProMentor 等是个别字段吗?或者在此处粘贴您的整个模型 User.php

$criteria->compare('activated', $this->activated);   
    $criteria->compare('disable', $this->disable);
    $criteria->compare('isProMentor', $this->isProMentor);
    $criteria->compare('isPerMentor', $this->isPerMentor);
    $criteria->compare('isDomMentor', $this->isDomMentor);
    $criteria->compare('isStudent', $this->isStudent);
    $criteria->compare('isMentee', $this->isMentee);

【讨论】:

  • 我想我明白了。我将我的逻辑添加到了 search() 方法,但是当提交发生时我似乎无法让它做任何事情。激活、禁用和所有列出的都有单独的字段。如果按字段表示数据库中的列,是的。我没有创建数据库,所以这只是我必须使用的东西。
  • 还包括用户的整个模型,所以你可以看到我做了什么。
  • 第二次看这个捕获的究竟是什么?我需要命名我的下拉内容吗? $countryVal=Yii::app()->session['admincntry'];
  • 仍然坚持这个有什么反馈吗?
  • 您好 jsan,抱歉回复晚了。我在上面给出了例子。我正在使用这个 Yii::app()->session['admincntry']; 从会话中检索登录用户的国家/地区。你为什么使用“项目导师”、“个人导师”、“领域导师”、“被指导者”作为单独的字段是有意完成或要求的。是不是在搜索功能中没有获取到提交的数据?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-16
  • 2015-10-19
  • 1970-01-01
  • 2011-09-08
  • 1970-01-01
相关资源
最近更新 更多