Yii dropDownList — где сделать логику для выбранного элемента

Я пытаюсь захватить значение, выбранное из dropDownList из CActiveForm, а затем выполнить некоторую логику после отправки …, чтобы затем выполнить запрос. Основываясь на этом запросе, я бы обновил сетку. Эта форма не имеет никаких атрибутов в таблице, которые относятся к ней, но, тем более, я могу создать фильтр для своего GridView после некоторой логики.

Где бы я выполнил эту логику? Я новичок в php, yii и javascript, поэтому я хотел бы, по крайней мере, указать мне правильное направление. Я пытался просмотреть документацию и книги yii, но не нашел то, что мне нужно. я думаю, что я пропускаю что-то критическое из php и web dev, чтобы застрять на чем-то таком тривиальном, как выпадающий список.

Это мой взгляд на admin.php, который затем вызывает метод advanced_search.php с помощью renderPartial.

    <?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'),
),
)));
?>

мой advanced_search.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;
}

0

Решение

ОК, я не знаю, какую логику вы пытались. Я предполагаю, что вы хотите перечислить данные на основе критериев поиска, указанных в advanced_search.php. Вам нужно написать логику для результатов в функции поиска.

Если вы не можете понять, дайте мне знать. Также активированы, отключены, 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);
-1

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]