How to avoid codeigniter skipping empty URL parameters - codeigniter

I am using Codeigniter with the following URL (as a sample)
domain.com/index.php/controller/method/p1/p2/p3
The problem is one of functions sometimes doesn't return p2. This has resulted in the following url
domain.com/index.php/controller/method/p1//p3
In my controller, I have the method set as follows:
public function (p1 = FALSE, p2 = FALSE, p3 = FALSE) {code}
However, when p2 is empty as above, suddenly p2 doesn't return false but instead returns p3 and p3 doesn't return anything. Why is this and how to avoid? (I have searched extensively but can't seem to work out what the issue is)

to prevent missing parameter issues you should use the following code
make your routes like below
$route['(.*)'] = 'controller/method';
.* => it will return all parametar after the method
update your function as below
public function () {
$controller = $this->uri->segment(1); // controller
$method = $this->uri->segment(2); // method
$param1 = $this->uri->segment(3); // p1
$param2 = $this->uri->segment(4); // p2
$param3 = $this->uri->segment(5); // p3
}

Related

How to merge all models in laravel?

I want to show all slideshow when the images are not blank.
public function index()
{
$slideAdvertise = Advertise::whereNotNull('image')->get();
$slideDesignStudio = DesignStudio::whereNotNull('image')->get();
$slideHouse = House::whereNotNull('image')->get();
$slidePhotographer = Photographer::whereNotNull('image')->get();
$slideWebsite = Website::whereNotNull('image')->get();
$slideShows = $slideAdvertise->merge($slideDesignStudio)->merge($slideHouse)->merge($slidePhotographer)->merge($slideWebsite);
return view('Home.index', compact('slideShows'));
}
Note: This code does not even have an error.
There are two things you are missing.
First the all() function at the end of the merge calls.
$slideShows = $slideAdvertise->merge($slideDesignStudio)->merge($slideHouse)->merge($slidePhotographer)->merge($slideWebsite)->all();
Second is to use arrays in case a query returns no results.
public function index()
{
$slideAdvertise = Advertise::whereNotNull('image')->get()->toArray();
$slideDesignStudio = DesignStudio::whereNotNull('image')->get()->toArray();
$slideHouse = House::whereNotNull('image')->get()->toArray();
$slidePhotographer = Photographer::whereNotNull('image')->get()->toArray();
$slideWebsite = Website::whereNotNull('image')->get()->toArray();
$slideShows = $slideAdvertise->merge($slideDesignStudio)->merge($slideHouse)->merge($slidePhotographer)->merge($slideWebsite)->all();
return view('Home.index', compact('slideShows'));
}

How to redirect to another page after submitting a form

How to redirect to another page after submitting a form with my controller. the form is working fine but when i use the code like this i get a blank page and if i use
return view('leave.signUp');
it works but still remains in the page of the form and i want it to be redirected to another page.
public function index(Request $request)
{
if($request->isMethod('POST')){
$employee = new Employee;
$employee->lname = $request->input('lname');
$employee->fname = $request->input('fname');
$employee->oname = $request->input('oname');
$employee->employee_id = $request->input('staffId');
$employee->college = $request->input('college');
//$employee->salary_level = $request->input('salaryGradeLevel');
$employee->employee_type = $request->input('staffType');
$employee->employee_category= $request->input('staffCategory');
$employee->date_of_first_appointment= $request->input('dateOfFirstAppointment');
$employee->date_of_last_appointment= $request->input('dateOfLastAppointment');
$employee->country = $request->input('country');
$employee->gender = $request->input('gender');
$employee->title = $request->input('title');
$employee->marital_status = $request->input('maritalStatus');
$employee->email = $request->input('email');
$employee->phone_number = $request->input('phoneNumber');
$employee->date_of_birth = $request->input('dateOfBirth');
$employee->place_of_birth = $request->input('placeOfBirth');
$employee->religion = $request->input('religion');
$employee->origin = $request->input('stateOfOrigin');
$employee->local_government_area = $request->input('localGovernmentArea');
$employee->address = $request->input('address');
$employee->permanent_address = $request->input('permanentAddress');
$employee->extra_curicullar_activities = $request->input('extraCuricularActivities');
$employee->save();
$nextOfKin = new NextOfKin;
$nextOfKin->employee_id = $employee->employee_id;
$nextOfKin->title = $request->input('Ntitle');
$nextOfKin->surname = $request->input('Nsurname');
$nextOfKin->firstname = $request->input('Nfirstname');
$nextOfKin->othername = $request->input('Nothername');
$nextOfKin->relationship = $request->input('Nrelationship');
$nextOfKin->email = $request->input('Nemail');
$nextOfKin->phone_number = $request->input('NphoneNumber');
$nextOfKin->contact_address = $request->input('Naddress');
$nextOfKin->save();
return redirect(route('application'));
}
}
this is my web.php
Route::match(['post','get'],'application', 'LeavessController#index');
Route::match(['post','get'],'signUp', 'signUpsController#index');
Route::get('approved', 'LeavesController#getLeaveApproved');
Route::match(['post','get'], 'leaveType', 'LeavesController#getleaveType');
Route::match(['post','get'], 'leaveDepartment', 'LeavesController#getleaveDepartment');
Route::get('allLeave', 'LeavesController#getallLeave');
Route::get('leaveViewDetails', 'LeavesController#getleaveViewDetails');
Route::get('/get-leave-days/{leaveType}', 'LeavesController#getLeaveDays');
return redirect()->route('application');
The param for route() is what you defined in your routes with name(...)
https://laravel.com/docs/7.x/redirects#redirecting-named-routes
Besides that, I recommend you to read the laravel docs about Controllers: https://laravel.com/docs/7.x/controllers#resource-controllers
The index is only for returning the database entries. For inserting data into the database use store .
To redirect to a "simple" URL use:
return redirect('home/dashboard');
(replace 'home/dashboard' with the actual URL you want to redirect to)
To redirect to a named route use:
return redirect()->route('login');
(where login is the name of your route)
https://laravel.com/docs/7.x/responses#redirects

How to call information from one model to another Codeigniter

I'm stuck on this from a while.Can't figured it out.I reed documantion, tried with several videos and tried like 10 different ways, nothing is working yet.So I have one view/model for one thing, in this example Destination and I have separate files for Offers.The controllers for both are in one file.I want tho the information that is in destination to go to Offers as well.Please help I can't figure out what I'm missing:
So here is the most important parts:
destination_model.php
<?php class Destination_model extends CI_Model
{
public function getDestinationDetails($slug) {
$this->db->select('
id,
title,
information
');
$this->db->where('slug', $slug);
$query = $this->db->get('destinations')->row();
if(count($query) > 0)
{
return $query;
}
else
{
// redirect(base_url());
}
}
public function getOffersByDestination($destination_id)
{
$this->db->select('
o.short_title,
o.price,
o.currency,
o.information,
o.long_title_slug,
oi.image,
c.slug as parent_category
');
$this->db->from('offers o');
$this->db->join('offers_images oi', 'oi.offer_id = o.id', 'left');
$this->db->join('categories c', 'c.id = o.category');
$this->db->group_by('o.id');
$this->db->where('o.destination', $destination_id);
$this->db->where('o.active', '1');
return $this->db->get();
} }
And then in the controller for offers I put this:
$this->load->model('frontend/destination_model');
$this->params['destination'] = $this->destination_model->getOffersByDestination($data->id);
All I need is the title and the information about the destination.
Here is the whole controller for the offers:
$data = $this->slugs_model->getOfferDetails(strtok($this->uri->segment(2), "."));
$this->load->model('frontend/offers_model');
$this->load->model('frontend/destination_model');
$this->params['main'] = 'frontend/pages/offer_details';
$this->params['title'] = $data->long_title;
$this->params['breadcumb'] = $this->slugs_model->getSlugName($this->uri->segment(1));
$this->params['data'] = $data;
$this->params['images'] = $this->slugs_model->getOfferImages($data->id);
$this->params['similar'] = $this->slugs_model->getSimilarOffers($data->category, $data->id);
$this->params['destination'] = $this->destination_model->getOffersByDestination($data->id);
$this->params['offers'] = $this->offers_model->getImportantOffers($data->offers, $data->category, $data->id);
You need to generate query results after you get it from model,
e.g: row_array(), this function returns a single result row.
here's the doc: Generating Query Results
try this:
$this->load->model('frontend/destination_model');
$data['destination'] = $this->destination_model->getOffersByDestination($data->id)->row_array();
$this->load->view('view_name', $data);
And in your view echo $destination['attribut_name'];,
or you can print the array, to see if it's work print_r($destination);

Magento2: Argument 1 [...] must be an instance of Magento\Framework\App\Helper\Context

First of all, I'm quite new to Magento 2, but I've used Magento 1.x for some time.
I've read a lot about how to solve DI-related problems, but I'm stuck on this one:
Exception #0 (Exception): Recoverable Error: Argument 1 passed to Cefar\AO\Helper\Ao::__construct() must be an instance of Magento\Framework\App\Helper\Context, instance of Magento\Framework\ObjectManager\ObjectManager given, called in .../vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php on line 93 and defined in .../Cefar/AO/Helper/Ao.php on line 11
Many other answers have suggested deleting the var/di and var/generation folders, sometimes var/cache also. While this solves the problem, it occurs again once bin/magento setup:di:compile is run, which means the code cannot be used in a production environment.
I've checked that the Ao class does not instantiate any objects. It also doesn't try to re-make any objects that could be provided by the context given. Here's the code:
namespace Cefar\AO\Helper;
class Ao extends \Magento\Framework\App\Helper\AbstractHelper
{
const DEFAULT_GRID_COLS = 4;
protected $_session;
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Customer\Model\Session $session
)
{
parent::__construct($context);
$this->_session = $session;
}
public function getConfig($path)
{
return $this->scopeConfig->getValue($path);
}
public function isActive($url = null, $print = true) {
$active = ($url && strstr($_SERVER['REQUEST_URI'], $url) !== false);
if ($active && $print) {
echo "active";
} else {
return $active;
}
}
public function isLoggedIn()
{
return $this->_session->isLoggedIn();
}
public function limitWords($text = '', $limit = 10, $showDots = true)
{
$words = explode(' ', $text);
$limited = array_slice($words, 0, $limit);
$newText = implode(' ', $limited);
if (count($words) > $limit && $showDots) {
$newText .= '...';
}
return $newText;
}
public function getCurrentGrid()
{
return ($this->_getRequest()->getParam('grid'))
? $this->_getRequest()->getParam('grid')
: self::DEFAULT_GRID_COLS;
}
}
There's nothing particularly special here. I'm confused as to how this is even happening; every other defined class in the extension is getting its DI parameters correctly. Why is the ObjectManager apparatus providing an unwanted argument? The relevant call is given in the error report as:
.../vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php(93): Cefar\AO\Helper\Ao->__construct(Object(Magento\Framework\ObjectManager\ObjectManager))
So it isn't even providing two arguments!
I've also read about providing type hints in a di.xml, but it doesn't seem to be relevant here as both types are part of the Magento libraries? I note that there is an entry for Magento\Framework\App\Helper\Context but not one for Magento\Customer\Model\Session... but that there are framework classes that use ID to import Magento\Customer\Model\Session already which work.
Long story short, this was because of a typo.
Sometimes when the helper was being included, it was being referred to as Cefar\AO\Helper\Ao, and other times, Cefar\AO\Helper\AO. Essentially, the ObjectManager was resolving both of these references to the same class, but it only had type hints for one of the names so it didn't know what to provide to the incorrect one.
A little help would have been nice, Magento! Maybe an error report that the requested class wasn't found? Still, at least this is finally over with.

Magento Custom Router loading controller but nothing else

I'm trying to get some custom routing going on in Magento using the following code (which I've only slightly modified from here https://stackoverflow.com/a/4158571/1069232):
class Company_Modulename_Controller_Router extends Mage_Core_Controller_Varien_Router_Standard {
public function match(Zend_Controller_Request_Http $request){
$path = explode('/', trim($request->getPathInfo(), '/'));
// If path doesn't match your module requirements
if ($path[1] == 'home.html' || (count($path) > 2 && $path[0] != 'portfolios')) {
return false;
}
// Define initial values for controller initialization
$module = $path[0];
$realModule = 'Company_Modulename';
$controller = 'index';
$action = 'index';
$controllerClassName = $this->_validateControllerClassName(
$realModule,
$controller
);
// If controller was not found
if (!$controllerClassName) {
return false;
}
// Instantiate controller class
$controllerInstance = Mage::getControllerInstance(
$controllerClassName,
$request,
$this->getFront()->getResponse()
);
// If action is not found
if (!$controllerInstance->hasAction($action)) {
return false;
}
// Set request data
$request->setModuleName($module);
$request->setControllerName($controller);
$request->setActionName($action);
$request->setControllerModule($realModule);
// Set your custom request parameter
$request->setParam('url_path', $path[1]);
// dispatch action
$request->setDispatched(true);
$controllerInstance->dispatch($action);
// Indicate that our route was dispatched
return true;
}
}
The result is a page where the template has loaded but with no content. If I comment out the $this->loadLayout() / $this->renderLayout() in my controller I can print to screen. But when I try and load a Template and/or Block it breaks somewhere.
home.html also loads fine (as the method returns false if the path is home.html).
Any assistance would be greatly appreciated.
I was implementing something similar to this and came across the same problem(That makes sense, because I copypasted your code)
before $request->setDispatched(true);
I added $request->setRouteName('brands'); (brands is the frontname of my module).
And It worked.Don't know if It'll work for you, but definetely there was something missing so that magento didn't know what layout to apply, because I could tell that teh controller was being reached.

Resources