Username changes with every new registration in YII framework - php

I am working on an application built with YII framework. Once the admin logins, the app redirects to dashboard where in the top right corner we can find the user name as SUPERADMIN. However, when i created a new registration form and adds a user, and on refreshing the dashboard page, instead of superadmin, i am seeing the newly registered user name. how to resolve this? below is the code.
dashboard url : http://localhost/myAPP/frontend/web/dashboard
Registration form URL: http://localhost/myApp/frontend/web/site/signup
in dashboard using <?php echo ucfirst(Yii::$app->user->identity->firstname); ?>
prints the username as SUPERADMIN. however the same code after new user registration showing the new user name. Please help.
Here is my signup code.
public function actionSignup()
{
$session = Yii::$app->session;
$labId = $session->get('labId');
if ($labId) {
if ($session->get('role') == 'super admin') {
$model = new SignupForm();
$success = NULL;
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
$success = "User registered successfully.";
$model = new SignupForm();
return $this->render('signup', [
'model' => $model, 'success' => $success,
]);
}
}
}
return $this->render('signup', [
'model' => $model,'success' => $success,
]);
} else {
return $this->goBack('../dashboard');
}
} else {
return $this->goBack('site/login');
}
}

Problem is in this line, if (Yii::$app->getUser()->login($user))
Why, I'm saying is. Because, Superadmin is registering user. So, there is no need of this line if (Yii::$app->getUser()->login($user)) {, because that new user no need to get login (as already Superadmin is logged in.) Remove that line and see.
if ($user = $model->signup()) {
$success = "User registered successfully.";
$model = new SignupForm();
return $this->render('signup', [
'model' => $model, 'success' => $success,
]);
}

Related

Yii2: Login form multiple index with select condition

I want to upgrade my application, with same login form but different index view, different application with in one login
the conditions what i want is if program "perjalanan dinas -> link to web/index.php" and if "file progress -> link to web/progress/index.php
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
$model->password = '';
return $this->render('login', [
'model' => $model,
]);
}
}

Yii2; code running in "else" block first, and then running code before "if" block?

I'm completely lost as to why this is happening, and it happens about 50% of the time.
I have a check to see if a user exists by email and last name, and if they do, run some code. If the user doesn't exist, then create the user, and then run some code.
I've done various testing with dummy data, and even if a user doesn't exist, it first creates them, but then runs the code in the "if" block.
Here's what I have.
if (User::existsByEmailAndLastName($params->email, $params->lastName)) {
var_dump('user already exists');
} else {
User::createNew($params);
var_dump("Creating a new user...");
}
And here are the respective methods:
public static function existsByEmailAndLastName($email, $lastName) {
return User::find()->where([
'email' => $email,
])->andWhere([
'last_name' => $lastName
])->one();
}
public static function createNew($params) {
$user = new User;
$user->first_name = $params->firstName;
$user->last_name = $params->lastName;
$user->email = $params->email;
$user->address = $params->address;
$user->address_2 = $params->address_2;
$user->city = $params->city;
$user->province = $params->province;
$user->country = $params->country;
$user->phone = $params->phone;
$user->postal_code = $params->postal_code;
return $user->insert();
}
I've tried flushing the cache. I've tried it with raw SQL queries using Yii::$app->db->createCommand(), but nothing seems to be working. I'm totally stumped.
Does anyone know why it would first create the user, and then do the check in the if statement?
Editing with controller code:
public function actionComplete()
{
if (Yii::$app->basket->isEmpty()) {
return $this->redirect('basket', 302);
}
$guest = Yii::$app->request->get('guest');
$params = new CompletePaymentForm;
$post = Yii::$app->request->post();
if ($this->userInfo || $guest) {
if ($params->load($post) && $params->validate()) {
if (!User::isEmailValid($params->email)) {
throw new UserException('Please provide a valid email.');
}
if (!User::existsByEmailAndLastName($params->email, $params->lastName)) {
User::createNew($params);
echo "creating new user";
} else {
echo "user already exists";
}
}
return $this->render('complete', [
'model' => $completeDonationForm
]);
}
return $this->render('complete-login-or-guest');
}
Here's the answer after multiple tries:
Passing an 'ajaxParam' parameters with the ActiveForm widget to define the name of the GET parameter that will be sent if the request is an ajax request. I named my parameter "ajax".
Here's what the beginning of the ActiveForm looks like:
$form = ActiveForm::begin([
'id' => 'complete-form',
'ajaxParam' => 'ajax'
])
And then I added this check in my controller:
if (Yii::$app->request->get('ajax') || Yii::$app->request->isAjax) {
return false;
}
It was an ajax issue, so thanks a bunch to Yupik for pointing me towards it (accepting his answer since it lead me here).
You can put validation like below in your model:
public function rules() { return [ [['email'], 'functionName'], [['lastname'], 'functionforlastName'], ];}
public function functionName($attribute, $params) {
$usercheck=User::find()->where(['email' => $email])->one();
if($usercheck)
{
$this->addError($attribute, 'Email already exists!');
}
}
and create/apply same function for lastname.
put in form fields email and lastname => ['enableAjaxValidation' => true]
In Create function in controller
use yii\web\Response;
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
else if ($model->load(Yii::$app->request->post()))
{
//place your code here
}
Add 'enableAjaxValidation' => false to your ActiveForm params in view. It happens because yii sends request to your action to validate this model, but it's not handled before your if statement.

Issue with Multiple renderAjax Forms Yii2

I am rendering ajax form
public function actionUser()
{
$model = new UserInfoForm();
$model->user_id = $this->user->id;
$validation = $this->performAjaxValidation($model);
if(null !== $validation){
return $validation;
}
$user = Yii::$app->user->identity;
return $this->renderAjax('user.php',[
'error' => $error,
'user' => $user,
'model' => $model
]);
}
And in user.php, i am having following line to get all user companies and jobs
Show User Companies and Jobs
Now in user details action
public function actiondetails()
{
$model = new UserJobsForm();
$validation = $this->performAjaxValidation($model);
if(null !== $validation){
return $validation;
}
$companies = Companies::getUserCompanies();
$jobs = BlogPost::getUserJobs();
return $this->renderAjax('user_info.php',[
'error' => $error,
'model' => $model,
'companies' => $companies,
'jobs' => $jobs
]);
}
In my user_info.php view page, i am able to see all the details. I am also seeing user.php view page, this is because, i am rendering user_info page on top of user.php. My requirement is not to open in new page. so i am trying to render on top of user.php. I want to close user.php as soon as user_info.php rendered. How can i do this??
If you just want to close another modal, you can call the script below in the user_info view
<script type="text/javascript">
$(function(){
$('#id_of_user_modal').modal('hide');
});
</script>

Finding the details of user in default login

I am trying to display the details like username and email of the user who logged in to their account. I am using default login of yii framework and I have profile table which authenticates the user. In fact I am trying to pass the username of the user as the parameters. This is the login action which checks for username and password.
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->redirect(Yii::$app->request->baseUrl.'/todo/index');
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login() )
{
return $this->redirect(Yii::$app->request->baseUrl.'/todo/index/<?php echo $model->username;?>'); //this is how i like to pass the username as parameter
}
return $this->render('login', [
'model' => $model,
]);
}
In Default LoginFrom Model data is under getUser function
So final code will be:
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->redirect(Yii::$app->request->baseUrl.'/todo/index');
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login() )
{
return $this->redirect(Yii::$app->request->baseUrl.'/todo/index/' . $model->getUser()->username); //this is how i like to pass the username as parameter
}
return $this->render('login', [
'model' => $model,
]);
}

Yii2 Auto login after registration

How can I achieve auto login after registration in yii2? In yii1, we achieved this through user Identity, but now I couldn't find it.
MY controller
public function actionCreate()
{
$model = new User();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->session->setFlash('success', 'Please Login with Email/Password!');
return $this->redirect('../site/login');
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
If registration is successful, I want to auto login instead of going site login.
if ($model->load(Yii::$app->request->post()) && $model->save()) {
\Yii::$app->user->login($model);
return $this->redirect(['/site/index']);
}
You can accomplish that with switchIdentity() method.
Example:
if ($userModel->load(Yii::$app->request->post()) && $userModel->save()) {
Yii::$app->user->switchIdentity($userModel); // log in
// do your stuff
}

Categories