IF Statement For Session - Formatting Q - codeigniter

So I have this IF statement in my view. it works and all, but wondering if there's a better way to write this. Having both session calls seem unneccessary...
if($this->session->userdata('campaign_name')){
echo $this->session->userdata('campaign_name');
}
else {
echo 'this';
}
Note this function will be used inline on a text input. So I'm looking for as minimal code as possible.

Note that CI's Session class's userdata method will return false if no campaign_name exists. So assign a variable to the potentially undefined array key (campaign_name)
$campaign_name = $this->session->userdata('campaign_name');
if($campaign_name)
{
echo $campaign_name;
}
else
{
echo 'this';
}
OR
if($campaign_name = $this->session->userdata('campaign_name'))
{
echo $campaign_name;
}
Controller Method (/application/controllers/test_controller.php)
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Test_Controller extends CI_Controller
{
function __construct()
{
parent::__construct();
}
public function myFunction()
{
$data['campaign_name'] = $this->session->userdata('campaign_name');
$this->load->view('test_view',$data);
}
}
View (/application/view/test_view.php)
<html>
<head></head>
<body>
<input type="text" value="<?php echo $campaign_name; ?>">
</body>
</html>

In your controller, you can store the value of that session data into a variable and pass that along to the view. In the view, you can then have your if else statements that just look at the variable. I would advise against setting a variable in the view as RPM did. While it works, it breaks the separation of concerns you have going.
Also, look into using the alternative PHP syntax for views in CodeIgniter. It'll make your code neater and more maintainable.
Edit: I see now that RPM has updated his answer to set the variable in the controller. That's a good example to follow.

Related

Passing the same variable to multiple laravel controller functions

I'm trying to create a variable accessible by two different controller functins in laravel. How can I do that. The first function gets a value from a blade, it stores it in a variable and then I want to pass that variable with value to another controller function. For example, the following blade passes obj_id to controller:
1) My blade:
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
<title>test</title>
</head>
<body>
<form method='post' action="/hard">
{{csrf_field()}}
<br>
<legend><i> Fill Data </i></legend>
<br>
<label>
OBJECT ID:
<input name='obj_id' type='text' minlength="8" required="" oninvalid="this.setCustomValidity('8 char at least')">
</label>
<br>
<input type='submit' value="Submit!">
</form>
<br>
<br>
</body>
</html>
2) My controller function Roger correctly gets obj_id (I have tested ot with dd)
public function Roger(Request $p)
{
$t = $p-> get('obj_id'); //I want $t to be global variable
//dd($t);
}
3) and then I want to pass $t to function Roger1 in the same controller
public function Roger1()
{
dd($t);
}
I have tried to declare $t as global with no success. I'm a little bit confused with $this and tried several combinations with no success.
Could you assist please?
You can use the session to store a variable
public function Roger(Request $p)
{
$t = $p-> get('obj_id'); //I want $t to be global variable
$p->session()->put('myvalue', $t);
}
public function Roger1(Request $p)
{
$p->session()->get('myvalue);
}
https://laravel.com/docs/5.8/session#storing-data
Scenatio #01
IF both methods are in the same controller AND your second method is called inside the first method (in the same call), you can just do:
class CoolController extends Controller {
public $var;
public function first_method(Request $value)
{
// Example 1: passing the value as a parameter:
$this->second_method($value);
// Example 2: passing the value through a class variable:
$this->var = $value; // $value: 'some-text'
$this->third_method();
}
public function second_method($value)
{
dd($value); // 'some-text'
}
public function third_method()
{
dd($this->var); // 'some-text';
}
}
Scenatio #02
Now, in the case you want to make a request from your view to set a value in your first method, and then another request calling your second method and getting that value that was "stored" in the first call.. well you can use any of this approaches. Why? because both call are in different lifecycles.
When the first call ended the value assigned in the first method (stored in memory) will be erased when the request is finished. That's why your second call will get a null value if you try to use it.
To store a temporary variable you have several paths:
Store it in the database.
Store it in the cache.
Send the value as a request parameter when doing the second call.

Unable to update session variable in CodeIgniter

I am in trouble using the CodeIgniter 2.2.6 session variables. I have a view, where some data is inputed by the user. Then, the user can press a submit button and this data goes to a web service, is processed and returned to the same view (using the controller and its model).
Bellow is the view code (v_index), where I save the data in the CodeIgniter session variables.
<?php
// loads the variables that will be used in print
$this->load->library('session');
$array_items = array(
'numberVehiclesUsed' => $numberVehiclesUsed,
'shortestRoute' => $shortestRoute,
'VRPSolution' => $VRPSolution,
);
$this->session->set_userdata($array_items);
?>
So, when I run the code bellow, I can see all the session data and everything is ok all the times. My application calls the web server, get the return and saves in the session variables everytime.
<?php
echo "<pre>";
print_r($this->session->all_userdata());
echo "</pre>";
?>
So, I have another screen where I want to use the session data, called "Imprimir" (it means print). The controller code is bellow. The print_r is the for debuging proposes, offcourse.
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class C_imprimir extends CI_Controller
{
function __construct()
{
parent::__construct();
//load the session library
$this->load->library('session');
}
public function index()
{
$dados['numberVehiclesUsed'] = $this->session->userdata('numberVehiclesUsed');
$dados['shortestRoute'] = $this->session->userdata('shortestRoute');
$dados['VRPSolution'] = $this->session->userdata('VRPSolution');
echo "<pre>";
print_r($this->session->all_userdata());
echo "</pre>";
$this->load->view('v_imprimir', $dados);
}
}
?>
When I run the code for the first time, it saves the data in the session variables and I am able to load in the controller "Imprimir" as the code above. The print_r shows that all the data is there and ok.
The problem is when I run the first view (v_index) again with new data, the session variables are updated but, the controller "Imprimir" loads only the first (and old) data, and never updates it.
I have no idea what I aḿ doing wrong. The others Stackoverflow questions about problems with CodeIgniter session variables did not help me.
Any suggestion?

Laravel 4: if statement in blade layout works strange

Could someone explain me why I get blank screen with printed string "#extends('layouts.default')" if I request page normally (not ajax)?
#if(!Request::ajax())
#extends('layouts.default')
#section('content')
#endif
Test
#if(!Request::ajax())
#stop
#endif
I'm trying to solve problem with Ajax, I don't want to create 2 templates for each request type and also I do want to use blade templates, so using controller layouts doesn't work for me. How can I do it in blade template? I was looking at this Laravel: how to render only one section of a template?
By the way. If I request it with ajax it works like it should.
Yes #extends has to be on line 1.
And I found solution for PJAX. At the beginning I was not sure this could solve my problem but it did. Don't know why I was afraid to lose blade functionality if you actually can't lose it this way. If someone is using PJAX and needs to use one template with and without layout this could be your solution:
protected $layout = 'layouts.default';
public function index()
{
if(Request::header('X-PJAX'))
{
return $view = View::make('home.index')
->with('title', 'index');
}
else
{
$this->layout->title = 'index';
$this->layout->content = View::make('home.index');
}
}
Try moving #extends to line 1 and you will see the blade template will render properly.
As for solving the ajax problem, I think it's better if you move the logic back to your controller.
Example:
…
if ( Request::ajax() )
{
return Response::eloquent($books);
} else {
return View::make('book.index')->with('books', $books);
}
…
Take a look at this thread for more info: http://forums.laravel.io/viewtopic.php?id=2508
You can still run your condition short handed in the fist line like so
#extends((Request::ajax())?"layout1":"layout2")

codeigniter - conditional if else statement using a href

I know this is a weird question, but let me explain more. I use codeigniter as framework to make my site. I have some code that contain if else condition in view and want to use that as a href so it becomes like a button that changes based on whether the condition has been met or not.
here is the code:
<?php if($this->tank_auth->is_logged_in())
{ echo anchor("auth/logout/","Logout");
} else {
echo anchor("auth/login/","Login");
?>
I was looking around in the net, but couldn't find a similar case where if else statement being used.
any idea how to achieve that?
Thanks
That should work fine, as long as tank_auth is loaded and you have a closing bracket after your else condition:
<?php
if($this->tank_auth->is_logged_in()) {
echo anchor("auth/logout/","Logout");
} else {
echo anchor("auth/login/","Login");
}
?>
You might also consider moving your check for the user's login to your controller, however, so as to keep tank_auth out of your views:
// ...end of controller function
$data['logged_in'] = $this->tank_auth->is_logged_in();
$this->load->view('my_view', $data);
}
In this case, you would then run your conditional on $logged_in in your view.

Call External Javascript function using Codeigniter

I need to call a javascript function from my controller in codeigniter.It is possible in codeigniter ?
Problem Details
My javascript file contains
function debugOutput(msg) {
alert (msg);
}
and also I need to call it from my controller.
I done it as follows.
<?php
function check()
{
header('Content-type: application/x-javascript');
// body here
}
?>
function execute() {
debugOutput("<?php echo 'test'; ?>");
}
execute();
But it is not working.Please help me to solve it.
Finally I got the answer.Here I am sharing that answer;
<?php function check(){
{header('Content-type: application/x-javascript');?>
function execute() {
showName(<?php echo 'ajithperuva';?>);
}
execute();
<?php
}
This script will invoke an external javascript function showName().
Thanks for all help me in my trouble.
For one, you would need to surround the call with <script> tags:
<script type="text/javascript">
function execute() {
...
}
</script>

Resources