Yii dropDownList - where to do logic for selected item - php
I'm trying to capture the value selected from a dropDownList from a CActiveForm and then do some logic on it after submit... to then run a query. Based on this query i would then update the gridview. This form doesn't have any attributes in a table that relate to it but its more so I can create a filter for my GridView after some logic.
Where would i perform this logic? I'm new to php, yii, and javascript so I'd appreciate at least pointing me to the right direction. I've tried to look at yii documentation and books but haven't found what i need. i think I'm missing something critical from php and web dev to be stuck on something so trivial as a drop down.
This is my view for admin.php which then calls the advanced_search.php form by 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'),
),
)));
?>
my 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>
my 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,
));
}
Update: as requested here is my 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;
}
OK I do not know what kind logic you were trying. I guess you want to list the data based on search criteria given in advanced_search.php. You need to write the logic for results in Search function.
If you are unable to understand let me know. Also activated, disable, isProMentor etc are individual fields? Or paste your entire model User.php here
$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);
Related
yii2 function issue called with null value
i'm trying to copy some values from a table that contain a column that relates to another table to copy too. the problem is that if i call the function createNew() of the model Email.php <?php namespace app\models; use Yii; /** * This is the model class for table "email". * * #property integer $id * #property integer $provider_id * #property integer $sender_id * #property string $recipient * #property string $name * #property string $cc * #property string $ccn * #property string $subject * #property string $body * #property integer $type * #property string $created * * #property Emailaccount $sender * #property Provider $provider */ class Email extends \yii\db\ActiveRecord { /** * #inheritdoc */ public static function tableName() { return 'email'; } /** * #inheritdoc */ public function rules() { return [ [['provider_id', 'sender_id', 'name', 'subject', 'body', 'type'], 'required'], [['provider_id', 'sender_id', 'type'], 'integer'], [['body'], 'string'], [['created'], 'safe'], [['recipient'], 'string', 'max' => 200], [['name', 'cc', 'ccn', 'subject'], 'string', 'max' => 100], [['sender_id'], 'exist', 'skipOnError' => true, 'targetClass' => Emailaccount::className(), 'targetAttribute' => ['sender_id' => 'id']], [['provider_id'], 'exist', 'skipOnError' => true, 'targetClass' => Provider::className(), 'targetAttribute' => ['provider_id' => 'id']], ]; } /** * #inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'provider_id' => 'Provider ID', 'sender_id' => 'Sender ID', 'recipient' => 'Recipient', 'name' => 'Name', 'cc' => 'Cc', 'ccn' => 'Ccn', 'subject' => 'Subject', 'body' => 'Body', 'type' => 'Type', 'created' => 'Created', ]; } /** * #return \yii\db\ActiveQuery */ public function getSender() { return $this->hasOne(Emailaccount::className(), ['id' => 'sender_id']); } /** * #return \yii\db\ActiveQuery */ public function getProvider() { return $this->hasOne(Provider::className(), ['id' => 'provider_id']); } public function createNew ($id,$new_id){ $model = Email::findOne(['id'=>$id]); $model->id = null; $model->provider_id = $new_id; $model->isNewRecord = true; $model->save(); return $model->id; } } from the model Service.php namespace app\models; use Yii; use app\models\Email; use app\models\Question; /** * This is the model class for table "service". * * #property integer $id * #property integer $provider_id * #property string $token * #property string $name * #property string $description * #property integer $parent_id * #property string $reference * #property integer $reference_id * #property integer $depth * #property integer $isleaf * #property string $color * #property string $icon * #property integer $type * #property string $type_label * #property integer $totem_reference_id * * #property Service $parent * #property Service[] $services */ class Service extends \yii\db\ActiveRecord { /** * #inheritdoc */ public static function tableName() { return 'service'; } /** * #inheritdoc */ public function rules() { return [ [['provider_id', 'token', 'name'], 'required'], [['provider_id', 'parent_id', 'reference_id', 'depth', 'isleaf', 'type', 'totem_reference_id'], 'integer'], [['reference', 'color'], 'string'], [['token', 'type_label'], 'string', 'max' => 45], [['name', 'description'], 'string', 'max' => 255], [['icon'], 'string', 'max' => 30], [['token'], 'unique'], [['parent_id'], 'exist', 'skipOnError' => true, 'targetClass' => Service::className(), 'targetAttribute' => ['parent_id' => 'id']], ]; } /** * #inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'provider_id' => 'Provider ID', 'token' => 'Token', 'name' => 'Name', 'description' => 'Description', 'parent_id' => 'Parent ID', 'reference' => 'Reference', 'reference_id' => 'Reference ID', 'depth' => 'Depth', 'isleaf' => 'Isleaf', 'color' => 'Color', 'icon' => 'Icon', 'type' => 'Type', 'type_label' => 'Type Label', 'totem_reference_id' => 'Totem Reference ID', ]; } /** * #return \yii\db\ActiveQuery */ public function getParent() { return $this->hasOne(Service::className(), ['id' => 'parent_id']); } /** * #return \yii\db\ActiveQuery */ public function getServices() { return $this->hasMany(Service::className(), ['parent_id' => 'id']); } public function mostraService($id,$new_id){ $service = Service::find() ->where(['provider_id'=>$id]) ->all(); foreach ($service as $s) { if ($s->parent_id==NULL) { $o_id= $s->id; //ID ORIGINALE $s->id= null; $s->token= Yii::$app->getSecurity()->generateRandomString(45); $s->isNewRecord = true; $s->provider_id = $new_id; //ID_NUOVO $s->save(); $p_id=$s->id; $copy = $this->recursiveCopy($o_id,$new_id,$p_id); } else { //do something } } } public function recursiveCopy ($id_s,$id_pr,$id_p){ $children = Service::find() ->where(['parent_id'=>$id_s]) ->all(); foreach ($children as $c) { if ($c->reference == null){ $o_id=$c->id; $c->id= null; $c->token= Yii::$app->getSecurity()->generateRandomString(45); $c->isNewRecord = true; $c->parent_id = $id_p; $c->provider_id = $id_pr; $c->save(); $c_id=$c->id; $copy = $this->recursiveCopy($o_id,$id_pr,$c_id); }else { if ($c->reference =='email') { $email = new Email(); $e_id=$email->createNew($c->reference_id, $id_pr); $c->id= null; $c->token = Yii::$app->getSecurity()->generateRandomString(45); $c->reference_id = $e_id; $c->provider_id = $id_pr; $c->parent_id = $id_p; $c->isNewRecord = true; $c->save(); } else if ($c->reference =='question'){ $question = new Question(); $q_id = $question->createNew($c->reference_id, $id_pr); } else { $c->id= null; $c->token = Yii::$app->getSecurity()->generateRandomString(45); $c->reference_id = $id_p; $c->provider_id = $id_pr; $c->parent_id = $id_p; $c->isNewRecord = true; $c->save(); } } } } } it work perfectly but if i call in the same way in the Question.php namespace app\models; use Yii; use app\models\Email; /** * This is the model class for table "question". * * #property integer $id *#property integer $provider_id * #property string $title * #property string $description * #property string $children * #property integer $parent_id * #property string $reference * #property integer $reference_id * #property integer $depth * #property integer $type * * #property Provider $provider * #property Question $parent * #property Question[] $questions */ class Question extends \yii\db\ActiveRecord { /** * #inheritdoc */ public static function tableName() { return 'question'; } /** * #inheritdoc */ public function rules() { return [ [['provider_id', 'title'], 'required'], [['provider_id', 'parent_id', 'reference_id', 'depth', 'type'], 'integer'], [['reference'], 'string'], [['title'], 'string', 'max' => 150], [['description'], 'string', 'max' => 1000], [['children'], 'string', 'max' => 300], [['provider_id'], 'exist', 'skipOnError' => true, 'targetClass' => Provider::className(), 'targetAttribute' => ['provider_id' => 'id']], [['parent_id'], 'exist', 'skipOnError' => true, 'targetClass' => Question::className(), 'targetAttribute' => ['parent_id' => 'id']], ]; } /** * #inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'provider_id' => 'Provider ID', 'title' => 'Title', 'description' => 'Description', 'children' => 'Children', 'parent_id' => 'Parent ID', 'reference' => 'Reference', 'reference_id' => 'Reference ID', 'depth' => 'Depth', 'type' => 'Type', ]; } /** * #return \yii\db\ActiveQuery */ public function getProvider() { return $this->hasOne(Provider::className(), ['id' => 'provider_id']); } /** * #return \yii\db\ActiveQuery */ public function getParent() { return $this->hasOne(Question::className(), ['id' => 'parent_id']); } /** * #return \yii\db\ActiveQuery */ public function getQuestions() { return $this->hasMany(Question::className(), ['parent_id' => 'id']); } public function createNew ($id,$new_id){ $model = Question::findOne(['id'=>$id]); $model->id= null; $model->provider_id = $new_id; $model->isNewRecord = true; $model->save(); $child= explode(",", $model->children); $sons= ''; foreach ($child as $c) { $model_c = Question::findOne(['id'=>$c]); $email = new Email(); $e_id=$email->createNew($model_c->reference_id,$new_id); $model_c->id= null; $model_c->provider_id = $new_id; $model_c->parent_id = $model->id; $model_c->isNewRecord = true; $model_c->save(); $sons=$sons.$model_c->id.','; } $model->children =$sons; } } it pass a null value and of course throw an exception. exception 1 exception 2 i tried to echo the value before pass it to the function and it print the right value. i really don't understand, someone can help me?
The problem is you are not checking if Model::findOne() has actually returned a valid result model. It could be false / null if the record with $id doesn't exist. The second error you are getting usually happens in following case: $object = null; $object->prop = 'a value'; aka whey you try to set a value of an object property which doesn't exist. And your first error message is saying that above case is true. app\models\Email::createNew(null, 51) <-- notice the null here So when you are finding a model always check before using it. You can do following: foreach ($child as $c) { $model_c = Question::findOne(['id'=>$c]); if( $model_c ) { // check the model is valid $email = new Email(); $e_id=$email->createNew($model_c->reference_id,$new_id); $model_c->id= null; $model_c->provider_id = $new_id; $model_c->parent_id = $model->id; $model_c->isNewRecord = true; $model_c->save(); $sons=$sons.$model_c->id.','; } } Just showed you one, do the rest. :)
Make join from 2 tables in Active Data Provider
I have 2 tables:User and Posts. User can have many posts,post can't have many users. How to build relations in that models and how to make Join in ActiveDataProvider I have user_id in my Posts table and want to show data in my gridview like Posts(id,title,text) and User(name) how can I do that?I need to make relations in my model and how can I use it?; Posts model: <?php namespace app\models; use Yii; /** * This is the model class for table "posts". * * #property integer $id * #property integer $user_id * #property string $post_title * #property string $post_text */ class Posts extends \yii\db\ActiveRecord { /** * #inheritdoc */ public static function tableName() { return 'posts'; } /** * #inheritdoc */ public function rules() { return [ [['user_id'], 'integer'], [['post_title'], 'string', 'max' => 50], [['post_text'], 'string', 'max' => 255], ]; } /** * #inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'user_id' => 'User ID', 'post_title' => 'Post Title', 'post_text' => 'Post Text', ]; } public function insertPost() { $userId = \Yii::$app->user->identity->id; $posts = new Posts(); $posts->user_id = $userId; $posts->post_title = $this->post_title; $posts->post_text = $this->post_text; return $posts->save(); } public function getUser() { return $this->hasOne(User::classname(),['user_id'=>'id']); } } User model: * #property integer $id * #property string $email * #property string $password * #property string $name */ class User extends \yii\db\ActiveRecord { /** * #inheritdoc */ public static function tableName() { return 'user'; } /** * #inheritdoc */ public function rules() { return [ [['email'], 'string', 'max' => 100], [['password'], 'string', 'max' => 255], [['name'], 'string', 'max' => 25], ]; } /** * #inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'email' => 'Email', 'password' => 'Password', 'name' => 'Name', ]; } public function setPassword($password) { $this->password = sha1($password); } public function validatePassword($password) { return $this->password === sha1($password); } public static function findIdentity($id) { return self::findOne($id); } public static function findIdentityByAccessToken($token, $type = null) { } public function getId() { return $this->id; } public function getAuthKey() { } public function validateAuthKey($authKey) { } public function getPost() { return $this->hasMany(Posts::classname(),['id'=>'user_id']); } }
You already have a relation (your function getPost ) in User model between User and Post you can access the the value of Post eg: $userModel = User::find()->where([ 'id' => $id])->one(); $myUserPost = $userModel->post; $myUserPostAttribute = $userModel->post->attribute; for ActiveDataProvider you can use $dataProvider = User::find()->where([ 'id' => $id]); and eventually add getter for single attribute in User Model eg: getMyPostAttribute1() { return $this->post->attribute1 } so you can easly use this getter in a gridview <?= GridView::widget([ 'dataProvider' => $dataProvider, ...... 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'myPostAttribute1', ....
How to call a method from model in YII 2 framework?
I am newbie in YII framework. I have installed correctly and created a Test Controller & Test Model using GII extension of YII. I have created a method in Model and want to access in Controller but unable to access. Test controller <?php namespace app\controllers\api; use Yii; use app\models\api\Test; use yii\web\Controller; use yii\web\NotFoundHttpException; class TestController extends \yii\web\Controller { public $modelClass = 'app\models\api\Test'; private $model; public function filters(){ return array( 'accessControl', // perform access control for CRUD operations array( 'RestfullYii.filters.ERestFilter + REST.GET, REST.PUT, REST.POST, REST.DELETE, REST.OPTIONS' ), ); } public function actions(){ return array( 'REST.'=>'RestfullYii.actions.ERestActionProvider', ); } public function accessRules(){ return array( array('allow', 'actions'=>array('REST.GET', 'REST.PUT', 'REST.POST', 'REST.DELETE', 'REST.OPTIONS'), 'users'=>array('*'), ), array('deny', // deny all users 'users'=>array('*'), ), ); } protected function loadModel( $id = null ) { if($this->model===null) { if($id!==null) $this->model=TestModel::model()->findByPk($id); } return $this->model; } public function actionIndex() { //return $this->render('index'); //$array = $modelClass::model()->listUserData(); //$array = Yii::app()->model()->listUserData(); //$array = $modelClass->listUserData(); // echo TestModel()->listUserData(); print "<pre>";print_r($this->model->listUserData()); exit; } } Test Model <?php namespace app\models\api; use Yii; /** * This is the model class for table "users". * * #property integer $id * #property string $username * #property string $password * #property string $email * #property string $activkey * #property integer $createtime * #property integer $lastvisit * #property integer $superuser * #property integer $status */ class Test extends \yii\db\ActiveRecord { /** * #inheritdoc */ public static function tableName() { return 'users'; } /** * #inheritdoc */ public function rules() { return [ [['username', 'password', 'email'], 'required'], [['createtime', 'lastvisit', 'superuser', 'status'], 'integer'], [['username'], 'string', 'max' => 50], [['password', 'email', 'activkey'], 'string', 'max' => 128], [['username'], 'unique'], [['email'], 'unique'], ]; } /** * #inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'username' => 'Username', 'password' => 'Password', 'email' => 'Email', 'activkey' => 'Activkey', 'createtime' => 'Createtime', 'lastvisit' => 'Lastvisit', 'superuser' => 'Superuser', 'status' => 'Status', ]; } public static function listUserData(){ $UserData = Test::model()->findAll('status = "0"'); return $UserData; } } i tried to search on forum but not able to resolve, please can you help me to resolve ? Thanks in advance.
In the controller. use pathtotestmodel/Test public function actionIndex() { $model = new Test(); $userdata = $model->listUserData(); } OR public function actionIndex() { $userdata = Test::listUserData(); }
Its simple create a instance of Model and then call the required function like public function actionIndex() { $model = new Test(); print "<pre>";print_r($model->listUserData()); exit; } Try this public static function listUserData(){ $UserData = Test::findAll(['status' =>0]);//in Yii2 //$UserData = Test::model()->findByAttributes(array( 'status' => 0 )); in yii 1.1 return $UserData; }
How to select users except roles with Laravel Eloquent
I need to select only id and name attribute from users table except roles attribute. I tried this: $school_user = User::select('name', 'id')->get()->toArray(); but when I print it to screen it returns array with his roles. Like this: Array ( [0] => Array ( [name] => Admin [id] => 1 [roles] => Array ( [0] => Array ( [id] => 3 [name] => admin [pivot] => Array ( [user_id] => 1 [role_id] => 1 ) ) ) ) ) Any suggestions to get only name and id attributes except roles? There is my User Model class (a bit cleaned): <?php use Illuminate\Auth\UserTrait; use Illuminate\Auth\UserInterface; use Illuminate\Auth\Reminders\RemindableTrait; use Illuminate\Auth\Reminders\RemindableInterface; class User extends Eloquent implements UserInterface, RemindableInterface { use UserTrait, RemindableTrait; /** * The database table used by the model. * * #var string */ protected $table = 'users'; /** * The attributes excluded from the model's JSON form. * * #var array */ protected $hidden = array('password', 'remember_token'); protected $fillable = array('email', 'name', 'password', 'block'); protected $guarded = array('id'); /** * Get the schools or kindergardens a user can moderate */ public function schools() { return $this->belongsToMany('School', 'school_user'); } /** * Get the roles a user has */ public function roles() { return $this->belongsToMany('Role', 'users_roles'); } /** * Find out if User is an employee, based on if has any roles * * #return boolean */ public function isEmployee() { $roles = $this->roles->toArray(); return !empty($roles); } /** * Find out if user has a specific role * * $return boolean */ public function hasRole($check) { return in_array($check, array_fetch($this->roles->toArray(), 'name')); } /** * Get key in array with corresponding value * * #return int */ private function getIdInArray($array, $term) { foreach ($array as $key => $value) { if ($value['name'] == $term) { return $key; } } throw new UnexpectedValueException; } /** * Add roles to user to make them a concierge */ public function makeEmployee($role_id) { $assigned_roles = array(); $roles = Role::all()->keyBy('id')->toArray(); $this->roles()->attach(array($role_id)); } public $invitation; protected static function boot() { parent::boot(); static::creating(function($model) { $data = array( 'invitation' => $model->invitation, 'email' => $model->email, 'name' => $model->name, 'password' => $model->password ); $model->password = Hash::make($model->password); $rules = array( 'invitation' => 'required', 'email' => 'unique:users,email|required|email', 'name' => 'required|min:3|max:20', 'password' => 'required|min:8|max:30' ); $validator = Validator::make($data, $rules); if ($validator->fails()) { throw new ValidationException(null, null, null, $validator->messages()); } else { return $model->validate(); } }); static::created(function($model) { $role_id = Invitation::where('code', '=', $model->invitation)->first()->role_id; $model->makeEmployee($role_id); $invitation_code = Invitation::where('code', '=', $model->invitation)->update(array('used_by' => $model->id)); }); } public function validate() { if (is_null(Invitation::where('code', '=', $this->invitation)->where('used_by', '=', '0')->first())) { throw new ValidationException(null, null, null, array('invitation' => "Грешен код.")); } else { return true; } } public function updatePass($old_password, $new_password, $repeat_new_password) { $data = array( 'old_password' => $old_password, 'new_password' => $new_password, 'repeat_new_password' => $repeat_new_password ); $rules = array( 'old_password' => 'required', 'new_password' => 'required|min:8|max:30', 'repeat_new_password' => 'required|same:new_password' ); $validator = Validator::make($data, $rules); if ($validator->fails()) { throw new ValidationException(null, null, null, $validator); } else { $user = User::find(Auth::user()->id); if (Hash::check($old_password, $user->password)) { $user->password = Hash::make($new_password); if($user->save()) { return true; } else { throw new ValidationException(null, null, null, array('mainError' => "Грешка с базата данни.")); } } else { throw new ValidationException(null, null, null, array('old_password' => "Моля въведете правилно страта Ви парола.")); } } } public function login($email, $password, $remember) { $data = array( 'email' => $email, 'password' => $password ); $rules = array( 'email' => 'required|email', 'password' => 'required' ); $validator = Validator::make($data, $rules); if ($validator->fails()) { throw new ValidationException(null, null, null, $validator); } else { if (User::where('email', '=', $email)->first()->block == true) { throw new ValidationException(null, null, null, array('mainError' => "Акаунтът ви е блокиран.")); } else { $remember = ($remember) ? true : false; if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) { return true; } else { throw new ValidationException(null, null, null, array('mainError' => 'Имейлът или паролата е грешна.')); } } } } } And Role Model: <?php class Role extends Eloquent { /** * The database table used by the model. * * #var string */ protected $table = 'roles'; protected $fillable = array('name'); protected $guarded = array('id'); /** * Set timestamps off */ public $timestamps = false; /** * Get users with a certain role */ public function users() { return $this->belongsToMany('User', 'users_roles'); } } I'm sorry for use of bulgarian language in exceptions
Looking at the code it's rather not possible that running just: $school_user = User::select('name', 'id')->get()->toArray(); make appending roles to result. You should make sure that you don't add anything to $appends property and you don't load relationship somewhere in your code. You should also make sure that you don't have custom toArray() method implemented that loads this relationship when converting to array. If you are sure you don't you should show the full code and your exact Laravel version. EDIT You didn't show where you launch your code with select or lists however you load your roles relationship in many methods - for example isEmployee, isEmployee or hasRole. That's why roles are used when you are converting to array. You might want to write your custom toArray method to remove roles from your result set when converting to array.
I want to Add attachment on ZendF2 Email but I cant understand what I do with following code?
Following is the code which I am using for sending email but tell me How I can add attachement with this ??Following is the code which I am using for sending email but tell me How I can add attachement with this ?? <?php namespace Application\Controller; use Application\Filter\DomainFilter; use Application\Form\DomainForm; use Application\Form\SendForm; use Application\Model\AccountModel; use Application\Model\CustomersModel; use Application\Model\DomainModel; use Application\Model\UploadModel; use Application\Service\Demo; use Zend\Crypt\BlockCipher; use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\ViewModel; /** * Class DomainController * #package Application\Controller */ class DomainController extends AbstractActionController { /** * #var DomainModel */ protected $_DomainModel; /** * #var DomainForm */ protected $_DomainForm; /** * #var SendForm */ protected $_SendForm; /** * #var AccountModel */ protected $_AccountModel; /** * #var UploadModel */ protected $_UploadModel; /** * #var CustomersModel */ protected $_CustomersModel; /** * #var SettingModel */ protected $_SettingModel; /** * #var Demo */ protected $_Demo; /** * #param \Application\Service\Demo $Demo */ public function setDemo($Demo) { $this->_Demo = $Demo; } /** * #return \Application\Service\Demo */ public function getDemo() { return $this->_Demo; } /** * #param \Application\Model\CustomersModel $CustomersModel */ public function setCustomersModel($CustomersModel) { $this->_CustomersModel = $CustomersModel; } /** * #return \Application\Model\CustomersModel */ public function getCustomersModel() { return $this->_CustomersModel; } /** * #param \Application\Model\UploadModel $UploadModel */ public function setUploadModel($UploadModel) { $this->_UploadModel = $UploadModel; } /** * #return \Application\Model\UploadModel */ public function getUploadModel() { return $this->_UploadModel; } /** * #param \Application\Form\DomainForm $DomainForm */ public function setDomainForm($DomainForm) { $this->_DomainForm = $DomainForm; } /** * #return \Application\Form\DomainForm */ public function getDomainForm() { return $this->_DomainForm; } /** * #param \Application\Model\DomainModel $DomainModel */ public function setDomainModel($DomainModel) { $this->_DomainModel = $DomainModel; } /** * #return \Application\Model\DomainModel */ public function getDomainModel() { return $this->_DomainModel; } /** * #param \Application\Model\AccountModel $AccountModel */ public function setAccountModel($AccountModel) { $this->_AccountModel = $AccountModel; } /** * #return \Application\Model\AccountModel */ public function getAccountModel() { return $this->_AccountModel; } /** * #return the $_SendForm */ public function getSendForm() { return $this->_SendForm; } /** * #param field_type $_SendForm */ public function setSendForm($_SendForm) { $this->_SendForm = $_SendForm; } /** * #param mixed $SettingModel */ public function setSettingModel($SettingModel) { $this->_SettingModel = $SettingModel; } /** * #return mixed */ public function getSettingModel() { return $this->_SettingModel; } /** * Domain * #return array|ViewModel */ public function indexAction() { return new ViewModel(array( 'domain' => $this->getDomainModel()->getList(), 'message' => $this->flashMessenger()->getMessages() )); } /** * Add Domain * #return \Zend\Http\Response|ViewModel */ public function addAction() { $request = $this->getRequest(); $form = $this->getDomainForm(); $form->setData(array('expired' => date('d/m/Y', strtotime('+1 year')))); $Adapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'); $BC = $this->getServiceLocator()->get('block_cipher'); $blockCipher = BlockCipher::factory('mcrypt', array('algo' => $BC['algo'])); $blockCipher->setKey($this->ApiKey()->getApiKey()); if (true === $request->isPost()) { $post = $request->getPost()->toArray(); $form->setData($post); $form->setInputFilter(new DomainFilter($Adapter, 0)); if (true === $form->isValid()) { $post['created'] = date('Y-m-d H:i:s'); $post['expired'] = date('Y-m-d', $this->FormatDates()->getDateToMkTime($post['expired'])); $post['pwd_ftp'] = $blockCipher->encrypt($post['pwd_ftp']); $this->getDomainModel()->insert($post); $this->flashMessenger()->addMessage(array('success', 1)); return $this->redirect()->toRoute('domain'); } } return new ViewModel(array( 'form' => $form )); } /** * Edit Domain * #return \Zend\Http\Response|ViewModel */ public function editAction() { $ID = (int)$this->params()->fromRoute('id', 0); $row = $this->getDomainModel()->find(array('d.id' => $ID)); $Adapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'); $BC = $this->getServiceLocator()->get('block_cipher'); $blockCipher = BlockCipher::factory('mcrypt', array('algo' => $BC['algo'])); $blockCipher->setKey($this->ApiKey()->getApiKey()); if (empty($row)) { $this->getResponse()->setStatusCode(404); return; } $request = $this->getRequest(); $form = $this->getDomainForm(); $row['pwd_ftp'] = $blockCipher->decrypt($row['pwd_ftp']); $row['expired'] = date('d/m/Y', strtotime($row['expired'])); $form->setData($row); if (true === $request->isPost()) { $post = $request->getPost()->toArray(); $form->setData($post); $form->setInputFilter(new DomainFilter($Adapter, $ID)); if (true === $form->isValid()) { $post['expired'] = date('Y-m-d', $this->FormatDates()->getDateToMkTime($post['expired'])); $post['pwd_ftp'] = $blockCipher->encrypt($post['pwd_ftp']); $this->getDomainModel()->update($ID, $post); $this->flashMessenger()->addMessage(array('success', 1)); return $this->redirect()->toRoute('domain'); } } return new ViewModel(array( 'form' => $form )); } /** * Delete Domain / Account * #return \Zend\Http\Response */ public function deleteAction() { $ID = (int)$this->params()->fromRoute('id', 0); $this->getDomainModel()->delete($ID); $this->getAccountModel()->deleteAllByDomain($ID); $this->getUploadModel()->deleteAllByDomain($ID); $this->flashMessenger()->addMessage(array('success', 1)); return $this->redirect()->toRoute('domain'); } /** * Detaglio Domain * #return ViewModel */ public function detailAction() { $ID = (int)$this->params()->fromRoute('id', 0); $domain = $this->getDomainModel()->find(array('d.id' => $ID)); if (empty($domain)) { $this->getResponse()->setStatusCode(404); return; } return new ViewModel(array( 'domain' => $domain, 'account' => $this->getAccountModel()->getList(array('a.id_domain' => $ID)), 'upload' => $this->getUploadModel()->getList(array('id_domain' => $ID)), 'type_ftp' => $this->getServiceLocator()->get('type_ftp') )); } /** * Send Domain * #return \Zend\Http\Response|ViewModel */ public function sendAction() { $ID = (int)$this->params()->fromRoute('id', 0); $domain = $this->getDomainModel()->find(array('d.id' => $ID)); $request = $this->getRequest(); $BC = $this->getServiceLocator()->get('block_cipher'); $blockCipher = BlockCipher::factory('mcrypt', array('algo' => $BC['algo'])); $blockCipher->setKey($this->ApiKey()->getApiKey()); if (empty($domain)) { $this->getResponse()->setStatusCode(404); return; } if (true === $request->isPost()) { $post = $request->getPost()->toArray(); $array_email = array(); if (isset($post['info_domain'])) { $array_email['info_domain'] = array( 'fullname' => $domain['fullname'], 'url' => $domain['url'], 'auth_code' => $domain['auth_code'], 'name_provider' => $domain['name_provider'], 'name_hosting' => $domain['name_hosting'], 'name_server' => $domain['name_server'] ); } if (isset($post['hosting_info'])) { $pwd_ftp = !empty($domain['pwd_ftp']) ? $blockCipher->decrypt($domain['pwd_ftp']) : ''; $array_email['hosting_info'] = array( 'fullname' => $domain['fullname'], 'url' => $domain['url'], 'pwd_ftp' => $pwd_ftp, 'port_ftp' => $domain['port_ftp'], 'name_hosting' => $domain['name_hosting'], 'name_server' => $domain['name_server'] ); } if (isset($post['ftp'])) { $pwd_ftp = !empty($domain['pwd_ftp']) ? $blockCipher->decrypt($domain['pwd_ftp']) : ''; $array_email['ftp'] = array( 'host_ftp' => $domain['host_ftp'], 'user_ftp' => $domain['user_ftp'], 'pwd_ftp' => $pwd_ftp, 'port_ftp' => $domain['port_ftp'], ); } if (isset($post['email_info'])) { $array_email['email_info'] = array( 'fullname' => $domain['fullname'], 'url' => $domain['url'] ); } if (isset($post['account']) && is_array($post['account'])) { $cnt = 0; foreach ($post['account'] as $key => $value) { $info_account = $this->getAccountModel()->find(array( 'a.id' => $value )); $pwd = !empty($info_account['pwd']) ? $blockCipher->decrypt($info_account['pwd']) : ''; $array_email['account'][$cnt] = array( 'name_type_account' => $info_account['name_type_account'], 'usermail' => $info_account['usermail'], 'pwd' => $pwd, 'info' => $info_account['info'], ); $cnt++; } } if (isset($post['note'])) { $array_email['note'] = $post['note']; } $sm = $this->getServiceLocator()->get('ServiceManager'); $translate = $sm->get('ViewHelperManager')->get('translate'); $setting = $this->getSettingModel()->find(array( 'id' => $this->WebStudioAuthentication()->getIdentity() )); $view = new ViewModel(array( 'data' => $array_email, )); $view->setTerminal(true); $view->setTemplate(sprintf('Application/view/email/send_data_%s', $setting['language'])); if ($this->getDemo()->getSendEmail() === true) { $this->mailerZF2()->send(array( 'to' => $post['email'], 'cc' => $post['usermail'], 'subject' => $translate('label_86', null, $setting['language']), ), $view); } $this->flashMessenger()->addMessage(array('success', 1)); return $this->redirect()->toRoute('domain/default', array('action' => 'send', 'id' => $ID)); } return new ViewModel(array( 'demo' => $this->getDemo()->getShowMessage(), 'domain' => $domain, 'datalist' => $this->getCustomersModel()->getList(), 'form' => $this->getSendForm(), 'account' => $this->getAccountModel()->getList(array('a.id_domain' => $ID)), 'message' => $this->flashMessenger()->getMessages() )); } } Here is the send form Code <?php namespace Application\Form; use Zend\Form\Form; /** * Class SendForm * #package Application\Form */ class SendForm extends Form { /** * #param string $name */ public function __construct($name = '') { parent::__construct($name); $this->setAttribute('method', 'post'); $this->setAttribute('class', 'bottom-margin'); $this->setAttribute('autocomplete', 'off'); $this->setAttribute('id', 'validateForm'); $this->add(array( 'name' => 'email', 'type' => 'Zend\Form\Element\Text', 'attributes' => array( 'class' => 'form-control', 'required' => 'required', 'list' => 'customers', ), )); $this->add(array( 'name' => 'note', 'type' => 'Zend\Form\Element\Textarea', 'attributes' => array( 'class' => 'form-control', ) )); } }