handle segments with in controller class in codeigniter 2.1 - php

i am stuck in segments in codeigniter because it is new to me,
the problem with my login form.
i gave the url in action like action="blog/login/getLog" and
my login form shows in the url like blog/login
i know that in controller class i just create a function like with the name login but i created my controller file like this:
class Blog extends CI_Controller{
function __construct(){
parent::__construct();
}
// Now See
function _remap( $method ){
$this->load->view('header');
switch( $method ){
case 'about':
$this->load->view('about');
break;
case 'login':
$this->load->view('login');
break;
case 'services':
$this->load->view('service');
break;
}
$this->load->view('footer');
}
}//Close Class
but now don't know how to handle both segment like login and login/getLog .
EDIT: What happen exactly, when i click on the login button then i just see the login form according to _remap() and the url like blog/login and when i submitted the form and the url looking like blog/login/getLog, the login form still looking but i want to redirect it on success.. or want to detect the segment getLog if possible in the case 'login': if possible.
Thanks in advanced.

If you are sending through the URL, just use uri class:
$var = $this->uri->segment(3);
If you are sending in a form, send the variable through the form. Perhaps a hidden field?
$var = $this->input->post('var_name');
Edit: I'm not quite sure why you are using _remap for this w/o routing to another function (you are only trying to call a view file instead)
This is how I would expect to see the login form:
<?php echo form_open('blog/login');?>
<input type="hidden" name="getLog" value"true" />
<input type="submit" value="Login" />
</form>
Then in your Blog class i would rather put a function
public function login() {
if($this->input->post('getLog') === "true") {
//the form was submitted, let's check the login?
}
else {
//probably don't need an else, but form isn't submitted
}
}
Edit 2:
In case there are confusions and you actually want to use remap. You can do it like this to get the variables also.
function _remap( $method ) {
if ($method == ‘something’) {
$this->something();
}
else {
$this->somethingelse();
}
}
function something() {
$var1 = $this->uri->segment(3);
$var2 = $this->input->post('some_variable_name');
}

class Blog extends CI_Controller{
function __construct(){
parent::__construct();
}
// Now See
function _remap( $method ){
switch( $method ){
case 'about':
$this->about(); <---------- here method (Add header, content, footer inside respective functions)
break;
case 'login':
$this->login(); <------- here too
break;
case 'services':
$this->service(); <----- here too
break;
}
}
}//Close Class
what you have done here is, you overrided the default behavior of URI by _remap function.
The overridden function call (typically the second segment of the URI)
will be passed as a parameter to the _remap() function:
Simply, in most cases, the 2nd segment will become $method in the _remap function.
so your form action will become.
action = "<?php echo base_url('blog/login');?>"
add index.php if you haven't removed index.php from your url by htaccess.
EDIT:
As per your question,
but now don't know how to handle both segment like login and login/getLog .
this is how you deal.
Any extra segments after the method name are passed into _remap() as an optional second parameter.
public function _remap($method, $params = array())
{
// all other segments will be in $paramas array
}

Related

Pass query string to same method in controller in codeigniter

I am Trying To Reload Contents Of Page. Through link button Filter In PHP
By Passing Some Value Through Query String To Controller Method.
The Controller Method Loads The Same Page From Where I am Passing Query String.
But The View Is Not Reloading.
But If I Call The Controller Method Some Other View It Works Fine.
here is my code
mainview.php
English
maincontroller.php
Here Is The Index Method Of Controller.
$movielanguage=$this->input->get('language');
if(!empty($movielanguage))
{
$moviedata['popularmovies']=$this->main_model-
>getmoviebylanguage($movielanguage);
}
$moviedata['allmovies']=$this->main_model->getAllMovies();
$this->load->view('home/mainview.php',$moviedata);
}
Here View Does Not Refresh Its Contents
How Can I Solve This
Hope this will help you :
First if you want a single view ,should put you code it in if else condition and second assign your data in same variable
Your code should be like this :
public function index()
{
$movielanguage=$this->input->get('language');
if(! empty($movielanguage))
{
$moviedata['movies']=$this->main_model->getmoviebylanguage($movielanguage);
}
else
{
$moviedata['movies']=$this->main_model->getAllMovies();
}
$this->load->view('home/mainview.php',$moviedata);
}
Second : and if you want to add different view for different category of movies
You can do like this :
public function index()
{
$movielanguage=$this->input->get('language');
if(! empty($movielanguage))
{
$moviedata['popularmovies']=$this->main_model->getmoviebylanguage($movielanguage);
/*popularview is just an example*/
$this->load->view('home/popularview.php',$moviedata);
}
else
{
$moviedata['allmovies']=$this->main_model->getAllMovies();
/*allview is just an example*/
$this->load->view('home/allview.php',$moviedata);
}
}

How to set two views in a controller in Zend framework

I'm trying to achieve a thank you page after submitting a form in Zend 1.12
in the index i have form and i want if the validation passes then should go to another view (NOT INDEX) for thank you page. how can i do this in my code:
public function indexAction()
{
// action body
$C_form = new Application_Form_Eform();
if ($this->_request->isPost()) {
$formData = $this->_request->getPost();
if ($C_form->isValid($formData)) {
$this->_helper->redirector('','result');
exit;
} else {
$C_form->populate($formData);
}
}
$this->view->form = C_eform;
}
and after that where should i create the .phtml file? in the application\views\scripts\index?
I think you're looking for render:
$this->view->render('index/yourotherview.phtml');
In this case, index/ is referring to your views/scripts/index folder, and the yourotherview.phtml file.
So, all together it would be:
public function indexAction()
{
// action body
$C_form = new Application_Form_Eform();
if ($this->_request->isPost()) {
$formData = $this->_request->getPost();
if ($C_form->isValid($formData)) {
$this->_redirect('/index/result);
} else {
$C_form->populate($formData);
}
}
$this->view->form = C_eform;
}
EDIT:
From your comment it looks like you just want to be redirected instead of displaying a different view. In this case, it's as easy as creating a new action and making the view for it:
public function resultAction() {
// Code here if you need it
}
Then create the file result.phtml in the index/ views directory, and you'll need $this->_redirect('/index/result'); in the index controller. (See above code)

Changing title of the page - determining whats the current page

I'm working on codeigniter and I wonder whats the best way to change title dynamically. Eg. title will change depending if you are on home page, single post page, category pages, etc.
The only solution i can think of is to make separate function and compare current URL ( from address bar ) with structure of the single post page, category page, home page
Something like this:
public function current_title() {
if($this->uri->segment(2) == 'post') {
// will return post title
}
if($this->uri->segment(2) == 'category') {
// will return archive title
}
if(current_url() == base_url()) {
// this is home page
}
If anyone worked with this before, any advice highly appreciated
I would not use the uri for this, but instead the controller and action name and the language class :
public function current_title()
{
$this->lang->load('titles.php', 'en');
return $this->lang->line(
$this->router->fetch_class().'.'.$this->router->fetch_method()
);
}
You will have a key like MyClass.myMethod for your translation. Just add your titles in your titles.php file :
$lang['MyClass.myMethod'] = "The title";
$lang['MyOtherClass.myOtherMethod'] = "The other title";
Read more about translation :
http://ellislab.com/codeigniter/user-guide/libraries/language.html
http://ellislab.com/codeigniter/user-guide/helpers/language_helper.html
//in the controller you should do like this:
class Home extends your_Controller {
public function __construct() {
parent:: __construct();
}
function index()
{
$this->data['pageTitle'] = 'Your page title';
$data['main_content'] = 'home';
$this->load->view('includefolder/viewname', $data);
}
}
This is how I do it:
$PHPFile = basename($_SERVER['PHP_SELF'],'.php');
switch ($PHPFile) {
case 'index': $PageTitle = 'Home'; break;
case 'products': $PageTitle = 'Products'; break;
case 'services': $PageTitle = 'Services'; break;
}
You can use string searches or whatever is needed. I use this method since I have the header of the page as a function in library.
As we have a controller function for each view so you can easily get function name from url
$this -> router -> fetch_module();
so you can work with it.

How does codeigniter know how to pass parameters from controller to the model

I am starting to learn codeigniters active record and i am querying my database using parameters passed from the controller to the model.
First i am passing the id from the controller to the model and that works.
Controller
function bret($id){
$this->load->model('school_model');
$data = $this->school_model->get_city_and_population($id);
foreach ($data as $row)
{
echo "<b>Name Of The City</b>...........". $row['Name'];
echo "<br/>";
echo "<b>Total Population</b>...........".$row['Population'];
}
}
Model
function get_city_and_population($id){
$this->db->select('Name,Population');
$query = $this->db->get_where('city', array('ID'=>$id));
return $query->result_array();
}
I went ahead and put in multiple parameters expecting to fail but this works but i am not so sure why it worked or what worked.
Controller
public function parameters($id,$name,$district){
$this->load->model('school_model');
$data = $this->school_model->multiple_parameters($id,$name,$district);
foreach ($data as $row)
{
echo "<b>Total Population</b>...........".$row['Population'];
}
}
Model
function multiple_parameters($id,$name,$district){
$this->db->select('Population');
$query = $this->db->get_where('city', array('ID'=>$id,'Name'=>$name,'District'=>$district));
return $query->result_array();
}
In my multiple parameters example i visited http://example.com/env/at/index.php/frontpage/parameters/7/Haag/Zuid-Holland/
Here,i know the name Haag is in id 7 and the district is Zuid-Holland
Here are my questions.How does codeigniter know how to pass the parameters from the url to the model and secondly,what if i was slightly wrong like 7/Haag/Zuid-Hollandes/,how would i show the user that,that url is wrong and fallback to a default value instead of showing blank when the parameters are wrong?.
//In codeiginter URI contains more then two segments they will be passed to your function as parameters.
//if Url: http://example.com/env/at/index.php/frontpage/parameters/7/Haag/Zuid-Holland/
//Controller: forntpage
public function parameters($id,$name,$district){
echo $id.'-'$name.'-'.$district;
}
//and if you are manually getting url from segment & want to set default value instead of blank then use following:
public function parameters(
$this->load->helper("helper");
$variable=$this->uri->segment(segment_no,default value);
//$id=$this->uri->segment(3,0);
}
//or
//Controller: forntpage
public function parameters($id='defaultvalue',$name='defaultvalue',$district='defaultvalue'){
echo $id.'-'$name.'-'.$district;
}
That's just simple uri mapping in CI, or uri param binding if you will.
When you have a method like:
public function something($param1, $param2) {
// get from: controller/something/first-param/second-param
}
That means your uri segments are passed as arguments to your controller method.
The above method could be written as:
public function something() {
$param1 = $this->uri->segment(3);
$param2 = $this->uri->segment(4);
// segment 1 is the controller, segment 2 is the action/method.
}
You need to understand that you have to manually check if the uri segments are exactly what you want them to be, as CI doesn't do anything else than this mapping.
Next, if you want to have some defaults, following statement is true:
public function something($param1 = 'some default value', $param2 = 'other value') {
// get from: controller/something/first-param/second-param
}
That is, if a url like: /controller/something is passed along, you will still get your default values back. When controller/something/test is passed, your first param is overridden by the one from the url (test).
That's pretty much it.

Codeigniter - Checking if a GET request is made

Im using CodeIgniter to write a site ... I understand $_GET requests are now used like so www.website.com/function/value .. and in the controller getting a url segment is written like so:
$userId = $this->uri->segment(3, 0);
Im just wondering, when a controller loads, i want to check if there is any uri segments, if there is then push to one view, else if there isnt a uri segment push to another.
Is that possible?
cheers.
You can use your controller arguments for that too.
When accessing /user/profile/1 your controller named User will call the method profile() and pass the number 1 as the first argument to your method. Like so:
class User extends CI_Controller {
{
public function index()
{
$this->load->view("user_index");
}
public function profile ( $userId = null )
{
if( (int)$userId > 0 )
$this->load->view("user_profile");
else
$this->load->view("another_view");
}
}
This is a very basic sample and I'm just trying to show the idea.
Seems like your asking two questions...
First, to check if the request is get
public function get_test()
{
if($_SERVER['REQUEST_METHOD'] == "GET")
{
//do something from get
echo "GET";
}
else
{
//do something not get
echo "NOT GET";
}
}
The next question seemed to be checking uri segments
public function get_test()
{
if($_SERVER['REQUEST_METHOD'] == "GET")
{
//do something from get
//echo "GET";
if($this->uri->segment(3)) //is true as is not empty
{
echo $this->uri->segment(3);
}
else
{
echo "I am nothing without my URI Segment";
}
}
else
{
//do something not get
echo "NOT GET";
}
}
As I understand you can use PHP default value.
function myFunction($var1 = NULL) {... if($var1 === NULL) ...}
Now if you do not pass the param you will get the NULL value.
I am still not using version 2 of codeigniter but this framework do not accept get requests; unless you mess with the configuration. Theres a function $this->input->get('myGet') you should look around at de the codeigniter.com/user_guide

Categories