GET url parameters Codeigniter - codeigniter-3

There is one view, and one controller, it is necessary, with the use of the get parameter, to change the path by the link. So in the end it turned out like this:
Upcoming -> http://mywebsite.com/tournaments?type=upcoming
Finished -> http://mywebsite.com/tournaments?type=finished

Here is the controller which will process your GET variable
Controller
<?php
class Demo_controller extends CI_Controller
{
public function demo($id)
{
echo $id; //the id which you will get in URL string
}
}
?>
View File where you will pass the Variable
<?php
$id = "1";//dyanmic id which will be pased with the form
echo form_open('demo/demos-function'.$id);
//in between your code
echo form_close
?>
Routes
Inside routes.php
$route['demo/demos-function/(:any)] = Demo_controller/demo/$1
No need to change the $1 it will explain the routes that it is having URL paramater.
So Ultimately Your link will be
https://localhost/demo/demos-function/1
https://localhost/demo/demos-function/2

In Codeigniter Url like this :
Upcoming -> http://mywebsite.com/controller/method/upcoming
Finished -> http://mywebsite.com/controller/method/finished
public function method_name()
{
$type = $this->uri->segment(3); // third level value of URL - Segment(1) is controller and followed by method and query string
if($type == 'upcoming')
{
echo $type;
$this->load->view('upcoming');
}
else
{
echo $type;
$this->load->view('finished');
}
}

Related

Slim 4 get all routes into a controller without $app

I need to get all registed routes to work with into a controller.
In slim 3 it was possible to get the router with
$router = $container->get('router');
$routes = $router->getRoutes();
With $app it is easy $routes = $app->getRouteCollector()->getRoutes();
Any ideas?
If you use PHP-DI you could add a container definition and inject the object via constructor injection.
Example:
<?php
// config/container.php
use Slim\App;
use Slim\Factory\AppFactory;
use Slim\Interfaces\RouteCollectorInterface;
// ...
return [
App::class => function (ContainerInterface $container) {
AppFactory::setContainer($container);
return AppFactory::create();
},
RouteCollectorInterface::class => function (ContainerInterface $container) {
return $container->get(App::class)->getRouteCollector();
},
// ...
];
The action class:
<?php
namespace App\Action\Home;
use Psr\Http\Message\ResponseInterface;
use Slim\Http\Response;
use Slim\Http\ServerRequest;
use Slim\Interfaces\RouteCollectorInterface;
final class HomeAction
{
/**
* #var RouteCollectorInterface
*/
private $routeCollector;
public function __construct(RouteCollectorInterface $routeCollector)
{
$this->routeCollector = $routeCollector;
}
public function __invoke(ServerRequest $request, Response $response): ResponseInterface
{
$routes = $this->routeCollector->getRoutes();
// ...
}
}
This will display basic information about all routes in your app in SlimPHP 4:
$app->get('/tests/get-routes/', function ($request, $response, $args) use ($app) {
$routes = $app->getRouteCollector()->getRoutes();
foreach ($routes as $route) {
echo $route->getIdentifier() . " → ";
echo ($route->getName() ?? "(unnamed)") . " → ";
echo $route->getPattern();
echo "<br><br>";
}
return $response;
});
From there, one can use something like this to get the URL for a given route:
$routeParser = \Slim\Routing\RouteContext::fromRequest($request)->getRouteParser();
$path = $routeParser->urlFor($nameofroute, $data, $queryParams);
With the following caveats:
this will only work for named routes;
this will only work if the required route parameters are provided -- and there's no method to check whether a route takes mandatory or optional route parameters.
there's no method to get the URL for an unnamed route.

How can i redirect to previous page after a form submit in codeigniter

I have a test function in controller which generates a form page.
public function testing()
{
$this->form_validation->set_rules('test', 'TEST', 'required');
if ($this->form_validation->run()) {
redirect($this->agent->referrer());
} else {
$data['title'] = 'Testing';
$data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
$this->load->view('templates/header', $data);
$this->load->view('pages/nonmember/testing', $data);
$this->load->view('templates/footer');
}
}
The code of testing view as below
<div id="message"><?php echo $message; ?></div>
<?php echo form_open(base_url()."testing");?>
<p>
<?php echo form_input('test');?>
</p>
<p><?php echo form_submit('submit', 'Submit');?></p>
<?php echo form_close();?>
If users come from another page lets say About page to testing page i want after submitting form properly they get redirected back to About page. But it is not being possible as referer agent is staying at the testing page, so after submit it is staying there and not redirecting to About page.
All you need is:
redirect($_SERVER['HTTP_REFERER']);
add this line in your controller's testing function
$this->session->set_flashdata('url',$this->agent->referrer());
change this in the function testing
if ($this->form_validation->run()) {
redirect($this->session->flashdata('url'));
} else {
$this->session->set_flashdata('url',$this->agent->referrer());
//load the view
}
...
or you can also submit an hidden field like,
form_hidden('rURL', $this->agent->referrer());
then simply use its value in the controller.
if ($this->form_validation->run()) {
redirect($this->input->post('rURL'));
} else {
...
Not sure if it is the best solution or not , but i found the solution working perfectly.
We need to write the referrer address in a file and to redirect we need to read from that file.
first we need to load the file helper.
$this->load->helper('file');
if ($this->form_validation->run())
{
redirect(read_file('referrer.php'));
}
else
{
$referrer = $this->agent->referrer();
//need to check wrong input submission and page refresh
if ($referrer != "http://localhost/CIpractice2/testing" && !empty($referrer))
{
write_file('referrer.php', $referrer);
}
//show the form
}
Please refer to codeIgniter's file helper documentation

unset session variable in zend view

I ll reframe my question based on some research I have done?
I need to store lot of errors separately like $_SESSION['client_error'],$_SESSION['state_error'] etc.
According to zend documentation do I have to store it like this for each error?
$client_error = new Zend_Session_Namespace(''client_error);
$state_error = new Zend_Session_Namespace('state_erro'); and so on?
This is my code in the controller.
I am storing it as
$this->view->state_error_message=$state_error;
After I echo $this->state_error in the view I want to unset it.
Ok here are few more things I tried:
In the controller in policyInfoAction:
session_start();
$error_message = new Zend_Session_Namespace('error_message');
$error_message="TEST";
$this->view->error_message=$error_message;
$this->_redirect('/pdp/client-info/');
In the view in client-info:
session_start();
<?php echo $this->error_message; ?>
This returns nothing.
Ok this is my updated code:
public function clientInfoAction()
{
$errors = new Zend_Session_Namespace('errors');
// get the error arrays
$client_errors = (isset($errors->client_error)) ? $errors->client_error : array();
$state_errors = (isset($errors->state_error)) ? $errors->state_error : array();
unset($errors->client_error, $errors->state_error); // delete from the session
// assign the values to the view
$this->view->client_errors = $client_errors;
$this->view->state_errors = $state_errors;
}
public function policyInfoAction()
{
if (count($arrErrors) > 0)
{
// The error array had something in it. There was an error.
$strError="";
foreach ($arrErrors as $error)
{
$strError="";
$errors->client_error = array();
$errors->state_error = array();
foreach ($arrErrors as $error)
{
$strError .= $error;
// to add errors to each type:
$errors->client_error['client_error'] = $strError;
$errors->client_error[] = $strError;
$this->_redirect('/pdp/client-info/');
}
}
}
When i echo $this->client_errors I get 'Array'
Here is some advice and suggestions that can hopefully get you on the right track.
First, when using Zend_Session and/or Zend_Session_Namespace, you never want to use PHP's session_start() function1. If you start a session with session_start(), and then try to use Zend_Session, it will throw an exception that another session already exists.
Therefore, remove all session_start() calls from your Zend Framework application.
Second, you mentioned you had a lot of messages you need to store, so this may not be the right thing for you, but see the FlashMessenger action helper. This allows you to set a message in a controller, and then access it on the next page request. The messages only live for one page hop, so after the next page load, they are deleted. You can store many messages with the FlashMessenger, but your access to them is not very controlled. You could use multiple flash messengers each in differen namespaces also.
To solve your problem in particular, you could just do something like this:
// in controller that is validating
$errors = new Zend_Session_Namespace('errors');
$errors->client_error = array();
$errors->state_error = array();
// to add errors to each type:
$errors->client_error['some_error'] = 'You had some error, please try again.';
$errors->client_error['other_error'] = 'Other error occurred.';
$errors->client_error[] = 'Other error, not using a named key';
$errors->state_error[] = MY_STATE_PARSING_0;
What is happening here is we are getting a session namespace called errors creating new properties for client_error and state_error that are both arrays. You don't technically have to use multiple Zend_Session_Namespaces.
Then to clear the messages on the next page load, you can do this:
// from controller again, on the next page load
$errors = new Zend_Session_Namespace('errors');
// get the error arrays
$client_errors = (isset($errors->client_error)) ? $errors->client_error : array();
$state_errors = (isset($errors->state_error)) ? $errors->state_error : array();
unset($errors->client_error, $errors->state_error); // delete from the session
// assign the values to the view
$this->view->client_errors = $client_errors;
$this->view->state_errors = $state_errors;
See also the source code for Zend_Controller_Action_Helper_FlashMessenger which can give you some idea on managing data in session namespaces.
I don't know if this will help you or not but here is the code for a controller that just takes an id from a form a gathers data based on that id an assigns that data to the session (to be used throughout the module) and then unsets that data when appropriate. and Never leaves the Index page.
<?php
class Admin_IndexController extends Zend_Controller_Action
{
//zend_session_namespace('location')
protected $_session;
/**
*set the layout from default to admin for this controller
*/
public function preDispatch() {
$this->_helper->layout->setLayout('admin');
}
/**
*initiaize the flashmessenger and assign the _session property
*/
public function init() {
if ($this->_helper->FlashMessenger->hasMessages()) {
$this->view->messages = $this->_helper->FlashMessenger->getMessages();
}
//set the session namespace to property for easier access
$this->_session = new Zend_Session_Namespace('location');
}
/**
*Set the Station and gather data to be set in the session namespace for use
* in the rest of the module
*/
public function indexAction() {
//get form and pass to view
$form = new Admin_Form_Station();
$form->setAction('/admin/index');
$form->setName('setStation');
$this->view->station = $this->_session->stationName;
$this->view->stationComment = $this->_session->stationComment;
$this->view->form = $form;
try {
//get form values from request object
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
$data = (object)$form->getValues();
//set session variable 'station'
$this->_session->station = $data->station;
$station = new Application_Model_DbTable_Station();
$currentStation = $station->getStation($this->_session->station);
$this->_session->stationName = $currentStation->station;
$this->_session->stationComment = $currentStation->comment;
//assign array() of stations to session namespace
$stations = $station->fetchAllStation();
$this->_session->stations = $stations;
//assign array() of bidlocations to session namespace
$bidLocation = new Application_Model_DbTable_BidLocation();
$bidLocations = $bidLocation->fetchAllBidLocation($this->_stationId);
$this->_session->bidLocations = $bidLocations;
$this->_redirect($this->getRequest()->getRequestUri());
}
}
} catch (Zend_Exception $e) {
$this->_helper->flashMessenger->addMessage($e->getMessage());
$this->_redirect($this->getRequest()->getRequestUri());
}
}
/**
*Unset Session values and redirect to the index action
*/
public function changestationAction() {
Zend_Session::namespaceGet('location');
Zend_Session::namespaceUnset('location');
$this->getHelper('Redirector')->gotoSimple('index');
}
}
just to be complete i start the session in the bootstrap. On the theory that if I need it great if not no harm.
protected function _initsession() {
//start session
Zend_Session::start();
}
this is all the view is:
<?php if (!$this->station): ?>
<div class="span-5 prepend-2">
<?php echo $this->form ?>
</div>
<div class="span-10 prepend-2 last">
<p style="font-size: 2em">Please select the Station you wish to perform Administration actions on.</p>
</div>
<?php else: ?>
<div class="span-19 last">
<?php echo $this->render('_station.phtml') ?>
</div>
<?php endif; ?>

Error in view file

I'm new to zend framework.I'm getting the following error when trying to view the page
Fatal error: Using $this when not in object context in D:\xampp\htdocs\neemjobs\application\views\scripts\register\index.phtml on line 1
class RegisterController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
$this->view->pageTitle = "Zend_Form Example";
$this->view->bodyCopy = "<p >Please fill out this form.</p>";
$form = new forms_ContactForm();
$this->view->form = $form;
}
}
My View is
<?php echo $this->pageTitle ;?>
<?php echo $this->bodyCopy ;?>
This is totally correct (on my Zend Framework installation goes perfectly, I just don't understand "in which way" are you using the Form... but, anyway, it works, so the "bug" is not there...

Embedding persistent login form Zend

I've seen this question asked already - but none of the answers really gelled for me, so I'm asking again: I want to embed a persistent login form (which will change into a nav bar if logged in) in the header bar for a site. Effectively, I want to be able to inject some controller logic into the layout.
After much research, I can see several ways that might achieve this - none of which seem ideally suited.
View Helpers seem suited to adding a suite of methods to the Zend_View object - but I don't want to write conditional code in the layout.phtml to trigger a method. Action helpers would help me remove that functionality and call it from a Controller - but that seems to be in poor favour from several quarters. Then there are plugins, which might be well suited in the dispatch/authentication loop.
So, I was hoping someone might be able to offer me some guidance on which way might best suit my requirements. Any help is greatly appreciated.
For those of you with a similair issue, this is how I ended up solving it (I'm using layout btw)
I registered a view helper in the Bootstrap:
protected function _initHelpers(){
//has to come after view resource has been created
$view = $this->getResource('view');
// prefix refers to the folder name and the prefix for the class
$view->addHelperPath(APPLICATION_PATH.'/views/helpers/PREFIX','PREFIX');
return $view;
}
Here's the view helper code - the actual authentication logic is tucked away in model code. It's a bit clumsy, but it works
class SB_UserLoginPanel extends Zend_View_Helper_Abstract {
public function __construct() {
$this->user = new SB_Entity_Users();
$this->userAccount = new SB_Model_UserAccount();
$this->request = Zend_Controller_Front::getInstance()->getRequest();
$this->form = $this->makeLoginForm();
$this->message='';
}
//check login
public function userLoginPanel() {
if(isset($_POST['loginpanel']['login'])) {
$this->processLogin();
}
if(isset($_POST['loginpanel']['logout'])) {
$this->processLogout();
}
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
$this->loginPanel = $this->getUserNav();
} else {
$this->loginPanel = $this->getLoginForm();
$this->loginPanel .= $this->getMessages();
}
return $this->loginPanel;
}
private function processLogin() {
if($this->form->isValid($_POST)){
$logindata = $this->request->getPost('loginpanel');
if($this->user->login($logindata['email'],$logindata['password'])) {
Zend_Session::rememberMe();
$redirect = new Zend_Controller_Action_Helper_Redirector();
$redirect->goToUrl('/account/');
return $this->getUserNav();
}else {
$this->message = '<p id="account_error">Account not authorised</p>';
}
}else {
$this->form->getMessages();
}
}
private function processLogout() {
if(isset($_POST['loginpanel']['logout'])) {
$this->user->logout();
$request_data = Zend_Controller_Front::getInstance()->getRequest()->getParams();
if($request_data['controller']=='notallowed') {
$redirect = new Zend_Controller_Action_Helper_Redirector();
$redirect->goToUrl('/');
}
}
}
private function makeLoginForm() {
}
private function getLoginForm(){
return $this->form;
}
private function getMessages(){
return $this->message;
}
private function getUserNav(){
//return partial/render
}
}
I then call this from the relevant part of the markup in the layout.phtml file.
<?php echo $this->doctype(); ?>
<head>
<?php
echo $this->headLink() ."\n";
echo $this->headScript() ."\n";
echo $this->headMeta() ."\n";
?>
<title><?php echo $this->escape($this->title) ."\n"; ?></title>
</head>
<div id="masthead">
<div id="userLoginPanel">
<?php echo $this->userLoginPanel(); ?>
</div>
</div>
<!--rest of layout-->
In principle, this should be an action helper, but after reading some less than favourable articles regarding Zend Action Helper - I opted for this method which did the trick.
Hope that helps!