cakephp 3 using for login another model than users auth - mysql

I'm trying to make a login from another model and I have an error.
This is my code for Student Model
var $name= 'Student';
public $components = array(
'Session',
'Auth' => array(
'loginAction' => array(
'controller' => 'students',
'action' => 'login',
'plugin' => 'students'
),
'authError' => 'Did you really think you are allowed to see that?',
'authenticate' => array(
'Form' => array(
'fields' => array(
'username' => 'username', //Default is 'username' in the userModel
'password' => 'password' //Default is 'password' in the userModel
)
)
)
)
);
StudentsController looks like
public function beforeFilter(Event $event) {
parent::beforeFilter($event);
$this->Auth->allow('login');
}
public function login() {
if($this->Session->check('Auth.Student')){
$this->redirect(array('action' => 'login'));
}
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->Session->setFlash(__('Welcome, '. $this->Auth->student('username')));
$this->redirect($this->Auth->redirectUrl());
} else {
$this->Session->setFlash(__('Invalid username or password'));
}
}
}
And the AppController is
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
}
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'students', 'action' => 'login'),
'loginAction' => array('controller' => 'students', 'action' => 'login'),
));
public function beforeFilter(Event $event) {
$this->Auth->authenticate=array (
'loginAction' => [
'controller' => 'Students',
'action' => 'login',
'plugin' => false,
],
'Basic' => ['userModel' => 'Students'],
'Form' => ['userModel' => 'Students']
);
}
And I have the following error
Component class SessionComponent could not be found.
How can I fix it?

Session was deprecated in cakePHP 3, How you are doing is for cake2. In cake 3 you can use RequestHandeler like,
$this->loadComponent('RequestHandler');
OR
public $components = array(
'RequestHandler'
);
then use,
$this->request->Session()->read/write/delete/destroy();
Hope this will work for you :).

Related

Yajra DataTable search bar is not working

I have used Left Join Query in file called "directoryDataTable.php. Now the problem is that Yajra DataTable search bar is not working. Its neither giving any error nor the search result.
My DataTable query function is al follows.
public function query()
{
$id = \Illuminate\Support\Facades\Auth::user()->id;
$directories = DB::table('directories')
->leftjoin('claimed', 'directories.id', '=','claimed.dir_id')
->select('directories.*')
->where('directories.user_id',$id)
->where('paymentStatus','1')
->whereNull('directories.deleted_at')
->orWhere('claimed.claimed_by',$id);
return $this->applyScopes($directories);
}
Please Help
Changed the query to,
public function query()
{
$id = \Illuminate\Support\Facades\Auth::user()->id;
$directories = DB::table('directories')
->leftjoin('claimed', 'directories.id', '=','claimed.dir_id')
->select('directories.*')
->where(function ($query) {
$query->where('directories.user_id',\Illuminate\Support\Facades\Auth::user()->id)
->orWhere('claimed.claimed_by',\Illuminate\Support\Facades\Auth::user()->id);
})
->where('paymentStatus','1')
->whereNull('directories.deleted_at')
;
return $this->applyScopes($directories);
}
and in get columns function, replace ['name' => 'YourTableName.ColumnName','data' => 'YourColumnName'] Like this.
private function getColumns()
{
return [
'dir_name' => ['name' => 'directories.dir_name', 'data' => 'dir_name'],
'phone_number' => ['name' => 'directories.phone_number', 'data' => 'phone_number'],
'address' => ['name' => 'directories.address', 'data' => 'address'],
'features' => ['name' => 'directories.features', 'data' => 'features', ],
'Status' => ['name' => 'directories.Status', 'data' => 'Status','searchable'=>false ],
'Subscription' => ['name' => 'directories.Subscription', 'data' => 'Subscription','searchable'=>false ]
];
}

Could not send email: unknown Cake\Network\Exception\SocketException in cakephp3

Okay I have been to almost all threads but I couldn't find the answer what I want.
Controller: RegistersController
namespace App\Controller;
use App\Controller\AppController;
use Cake\Auth\DefaultPasswordHasher;
use Cake\Event\Event;
use Cake\Mailer\Email;
use Cake\Routing\Router;
class RegistersController extends AppController
{
public function add()
{
$this->loadModel('Tbusers');
$tbusers = $this->Tbusers->newEntity();
if ($this->request->is('post'))
{
$tbusers = $this->Tbusers->patchEntity($tbusers, $this->request->data);
if ($this->Tbusers->save($tbusers)) {
$this->Flash->success(__('Yayie! You have been registered.'));
$baseurl = Router::url('/', true);
$email = base64_encode($this->request->data['email']);
$first_name = $this->request->data['fname'];
$last_name = $this->request->data['lname'];
$username = $first_name.' '.$last_name;
//$confirmation_link = $baseurl.'users/confirm/'.$email;
$email = new Email();
$email->template('email')
->subject('Student Portal - Signup')
->emailFormat('html')
->to($this->request->data['email'])
//->viewVars(['confirmation_link' => $confirmation_link,'username'=>$username])
->viewVars(['username'=>$username])
->from('dotnetdev555#gmail.com')
->send();
if ($email->send())
{
// Success
echo "mail sent";
}
else
{
echo "Mail not sent";
// Failure
}
return $this->redirect(['action' => 'add']);
}
}
Inside Template->Email->html I have file called
email.ctp
Hello <?php echo $username; ?>,<br/>
Thanks,<br/>
Jaymin Sejpal Founder at Student Portal
app.php
'EmailTransport' => [
'default' => [
'className' => 'Mail',
// The following keys are used in SMTP transports
'host' => 'smtp.elasticemail.com',
'port' => 2525,
'timeout' => 30,
'username' => 'dotnetdev555#gmail.com',
'password' => 'secret',
'client' => null,
'tls' => null,
'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
],
],
I don't know what I am missing to it. I am refferring this
http://book.cakephp.org/3.0/en/core-libraries/email.html for now.
The email host that you are using might be using smtp protocol , so in your app.php . Try editing you className parameter to 'Smtp'
'EmailTransport' => [
'default' => [
'className' => 'Smtp',
// The following keys are used in SMTP transports
'host' => 'smtp.elasticemail.com',
'port' => 2525,
'timeout' => 30,
'username' => 'dotnetdev555#gmail.com',
'password' => 'secret',
'client' => null,
'tls' => null,
'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
],
],

Cakephp 3.0 join in three table

I am trying to fetch the data from three table in cakephp 3.0
There is three table
1) size_category
2) sizes
3) sizerelations
Below is the file wise code
Model SizeCategoryTable.php
public function initialize(array $config)
{
parent::initialize($config);
$this->table('size_category');
$this->displayField('sizeCat_Id');
$this->primaryKey('sizeCat_Id');
// used to associate the table with user table (join)
$this->belongsTo('Users', [
'className' => 'Users',
'foreignKey' => 'CreatedBy',
'propertyName' => 'user'
]);
$this->hasMany(
'Sizerelations', [
'className' => 'Sizerelations',
'foreignKey' => 'Scat_Id',
'propertyName' => 'sizerelations'
]
);
}
Controller SizeCategoryController
public function index($id = null)
{
$customQuery = $this->SizeCategory->find('all', array(
'contain' => array(
'Users',
'Sizerelations' => array(
'Sizes' => array(
'fields' => array('id', 'Size_Code')
)
)
)
));
//debug();die();
$this->set('sizeCategory', $this->paginate($customQuery));
$this->set('_serialize', ['sizeCategory']);
}
I am greeting the error of Sizerelations is not associated with Sizes

Drupal custom form get and record current user

I looked up on the internet and write an custom module.
I want to add a form for people to add some information into database.
I use "data" module to create a table called "profile".
And my module's code is (addfood.module):
<?php
/**
* Implements hook_menu().
*/
function addfood_menu() {
$items['food/add'] = array(
'title' => '新增食物檔案',
'page callback' => 'addfood_page',
'access callback' => TRUE,
);
return $items;
}
/**
* Implements hook_permission.
*/
function addfood_permission() {
return array(
'addfood module' => array(
'title' => t('Addfood module permission'),
));
}
/**
* Returns form render array.
*/
function addfood_form($form, &$form_state) {
if (user_access('addfood module')) {
//Allowed
$form['name'] = array(
'#title' => t('名稱'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['calorie'] = array(
'#title' => t('卡路里'),
'#type' => 'textfield',
'#required' => TRUE,
'#description' => t('填寫卡路里(單位:千卡)'),
);
$form['water'] = array(
'#title' => t('水'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['protein'] = array(
'#title' => t('蛋白質'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['saturated_fat'] = array(
'#title' => t('飽和脂肪'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['trans_fat'] = array(
'#title' => t('反式脂肪'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['carbohydrates'] = array(
'#title' => t('碳水化合物'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['dietary_fiber'] = array(
'#title' => t('膳食纖維'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['cholesterol'] = array(
'#title' => t('膽固醇'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['sodium'] = array(
'#title' => t('鈉'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['sugars'] = array(
'#title' => t('糖'),
'#type' => 'textfield',
'#required' => TRUE,
);
$form['notes'] = array(
'#title' => t('Please explain your what makes you a prime candidate for our beta test'),
'#type' => 'textarea',
'#resizable' => TRUE,
'#description' => t('Beta spaces are limited, but let us know if there is a really good reason to let you in.'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
} else {
//Access denied
header('Location: ../user/login?destination=food/add');
}
}
/**
* Menu callback.
*/
function addfood_page() {
return drupal_get_form('addfood_form');
}
/**
* Submission handler for form_example -> Insert into database
*/
function addfood_form_submit($form, &$form_state) {
$fe_id = db_insert('profile')
->fields(array(
'name' => $form_state['values']['name'],
'calorie' => $form_state['values']['calorie'],
'water' => $form_state['values']['water'],
'protein' => $form_state['values']['protein'],
'saturated_fat' => $form_state['values']['saturated_fat'],
'trans_fat' => $form_state['values']['trans_fat'],
'carbohydrates' => $form_state['values']['carbohydrates'],
'dietary_fiber' => $form_state['values']['dietary_fiber'],
'cholesterol' => $form_state['values']['cholesterol'],
'sodium' => $form_state['values']['sodium'],
'notes' => $form_state['values']['notes'],
))
->execute();
drupal_set_message(t('HO GYA Submit!!!!'));
return $form;
}
?>
If I want to record who add the information automatically(by get the current username).
Anyone has idea how to do it? Thank you.
Figure is my table schema.
(source: libk.info)
You can use global user variable to get current user. You can test it:
<?php
global $user;
print_r($user->name);
?>

How to connect 3 tables in yii2 and display in Gridview then make sorting work correctly

I have used the gii tool to create crud application. I have 3 tables the tbl_targetcities, lib_cities, and lib_provinces. I was able to connect lib_cities to tbl_targetciteis but not the lib_provinces. And also the sorting of city / Municipality does not work. It seems that it sorts according ti the ID.
tbl_target_cities
lib_cities
lib_provinces
sample View
So far here is my relation in the model.
public function getCityName()
{
return $this->hasOne(LibCities::className(),['city_code'=>'city_code']);
}
in my view file...
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute'=>'city_code',
'value'=>'cityName.city_name'
],
[
'attribute'=>'prov code',
'value'=>'cityName.city_name'
],
'kc_classification',
'cluster',
'grouping',
'priority',
'launch_year',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
How to display the prov_name from lib_provinces???
EDIT to answer user2839376 question in the comment box
IN THE SEARCH MODEL CLASS
$query = TblSpBub::find();
$query->joinWith('brgyCode')->joinWith(['cityCode'])->joinWith(['cityCode.provCode']);
$covered= LibAreas::find()->where(['user_id'=>yii::$app->user->identity->id])->all();
$query->all();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['id'=>SORT_DESC]],
]);
$dataProvider->sort->attributes['city'] = [
'asc' => ['lib_Cities.city_name' => SORT_ASC],
'desc' => ['lib_Cities.city_name' => SORT_DESC],
];
$dataProvider->sort->attributes['province'] = [
'asc' => ['lib_provinces.prov_name' => SORT_ASC],
'desc' => ['lib_provinces.prov_name' => SORT_DESC],
];
In LibCities model add new relation:
public function getProvince()
{
return $this->hasOne(LibProvince::className(),['prov_code'=>'prov_code']);
}
And change getCityName relation. You should add with() for relation:
public function getCityName()
{
return $this->hasOne(LibCities::className(),['city_code'=>'city_code'])->with(['province']);
}
And in view correct your columnto this:
[
'attribute'=>'prov code',
'value'=>'cityName.province.prov_name'
],
You have to use the function relations() in models.
In tbl_target_cities model:
public function relations()
{
return array(
'city' => array(self::HAS_ONE, 'LibCities', 'city_code'),
);
}
In LibCities model :
public function relations()
{
return array(
'province' => array(self::HAS_ONE, 'LibProvinces', 'prov_code'),
'targets' => array(self::HAS_MANY, 'TargetCity', 'city_code',
);
}
This will allowed you to jump throw the LibCities model,
now you can simply acces to prov name like this :
$model->city->province->prov name;
Note : You need to have the 3 models defined.
EDIT
array(
'name' => 'province name',
'value' => $data->city->province->prov_name;
),
Done it, Heres how.
in addition to the above code (original post)
// in Model I added an additional function
public function getTaskowner()
{
return $this->hasOne(Tasks::className(), ['id' => 'task_id'])
->with(
['location','taskowner']
);
}
and in view i did this
....
'columns' => [
....
[
'class' => 'kartik\grid\DataColumn',
'value'=> 'tasks.location.taskowner.name',
.....
],
.....
and it worked
key points. used an array with the 'with->(..)' to include both then in the view added 'tasks.location.taskowner.name', to join them all