Issue with Multiple renderAjax Forms Yii2 - php

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>

Related

Update record in laravel shows not exist message ( Not Updating Record )

I have two separate APIs calls. One for click on edit page and another for update page:
The controller method when the user hits edit link:
public function EditList($page_id)
{
$listEdit= DB::table('page_master')->where('id',$page_id)->first();
return view('edit-list',compact('listEdit'));
}
and its route:
$router->get('/edit-List/{id}', 'AjaxController#EditList');
The above code successfully shows me the edit page where I will perform the update.
My next step is update record:
The controller method
public function updatePage($id)
{
$updatePage = $this->page->updatePage($id);
if(!$updatePage)
{
$resultArray = ['status' => 0, 'message' => 'Page not exist!'];
return Response::json( $resultArray, 400);
}
else{
$resultArray = ['status' => 1, 'message' => 'Page updated !'];
return Response::json($resultArray, 200);
}
}
and its routes:
Route::post('update/list/{id}',['uses' => 'ApiController#updatePage']);
Now when i click on update record it shows me the page does not exist even though the page is there in database but always showing the page does not exist page.
What should I change to make the routes work properly?
public function updatePage($id)
{
$updatePage = self::find($id);
if (is_null($updatePage)) {
return false;
}
$input = Input::all();
$updatePage->fill($input);
$updatePage->save();
return $updatePage;
}

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.

Username changes with every new registration in YII framework

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,
]);
}

Laravel 5 Redirect from a sub-method

I'm using Socialite to get user information from facebook. All is going well but my redirect isn't working
Sub-routes
I read that it's not possible to do a redirect from a submethod, or
any method that's not in your routes.
But how else can i redirect the user after I logged them in?
My URL looks like this after the successfull facebook handshake
http://tmdb.app/auth/login/facebook?code=AQBTKNZIxbfdBruAJBqZ8xx9Qnz...
Code
class SocialController extends Controller {
public function login(Authenticate $authenticate, Request $request)
{
return $authenticate->execute($request->has('code'), $this);
}
public function userHasLoggedIn($data)
{
$user = User::where('provider_id', $data->id)->first();
if( !$user )
{
$user = User::create([
'name' => $data->name,
'email' => $data->email,
'provider' => 'facebook',
'provider_id' => $data->id
]);
}
// NOT WORKING!
return redirect('test');
}
}
Your login function should be handling the redirect.
I'm guessing execute returns $data if the user is sucessfully logged in and false if not.
class SocialController extends Controller {
public function login(Authenticate $authenticate, Request $request)
{
if($data = $authenticate->execute($request->has('code'), $this))
{
$user = User::where('provider_id', $data->id)->first();
// maybe delegate the user creation to another class/service?
if( !$user )
{
$user = User::create([
'name' => $data->name,
'email' => $data->email,
'provider' => 'facebook',
'provider_id' => $data->id
]);
}
return redirect('test');
}
return redirect('fail_view');
}
}
You can do it using PHP header function in Laravel sub method. I try it and works properly. Hope it can help you.
// You can using the following code
$url= url("about-laravel");
header("Location:" . $url);
exit;
// Or using the following code to redirect and keep set flash message
$result= $this->yourMethod(); // return redirect($this->route)->with('flash_message', 'I\'m Flash Message'); for TRUE or NULL for false
if( $result ){
return $result;
}

Edit action in Yii framework

I am working on a web application that allow users to have video conferences. Users are allowed to create video conferences and I want them to be able to also edit the scheduled video conferences but I am having trouble implementing that. Please help.
Edit button in index.php view
$html .= CHtml::ajaxLink('Edit',
Yii::app()->createAbsoluteUrl('videoConference/update/'.$vc->id),
array(
'type'=>'post',
'data' => array('id' =>$vc->id,'type'=>'update'),
),
array( "visible" => $ismoderator, 'role' => "button", "class" => "btn btn-info")
);
Video conference Controller actionUpdate
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model = $this->loadModel($id);
if (isset($_POST['VideoConference'])) {
$model->attributes = $_POST['VideoConference'];
if ($model->save())
$this->redirect(array('view', 'id' => $model->id));
}
$this->render('edit', array(
'model' => $model,
));
}
The first step is to find where is problem(frontend / backend). You need call action without ajax(just from url with param id). Try my version:
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model = $this->loadModel($id);
if ($model == null) {
throw new CHttpException(404, 'Model not exist.');
}
//if (isset($_POST['VideoConference'])) {
//$model->attributes = $_POST['VideoConference'];
$model->attributes = array('your_attr' => 'val', /* etc... */);
// or try to set 1 attribute $model->yourAttr = 'test';
if ($model->validate()) {
$model->update(); //better use update(), not save() for updating.
$this->redirect(array('view', 'id' => $model->id));
} else {
//check errors of validation
var_dump($model->getErrors());
die();
}
//}
$this->render('edit', array(
'model' => $model,
));
}
If on server side all working fine(row was updated) then check request params, console, tokens etc. Problem will be on frontend.
After troubleshooting a little I finally got it to work.
On the view I am calling the actionUpdate method like this:
$html .= CHtml::button('Edit', array('submit' => array('videoConference/update/'.$vc->id), "visible" => $ismoderator, 'role' => "button", "class" => "btn btn-info"));
On the controller just changed
$model->save() to $model->update()
and it works perfectly fine.

Categories