one controller for three pages - codeigniter

I have one controller ADD. I want this controller to manipulate three pages: add_customer page, add_project page and add_post_page.In this case add_project page works perfectly. But add_customer and add_post pages have errors:
Failed to load resource: the server responded with a status of 500 (Internal Server Error).
I think the problem is in my coditions here:
public function index(){
if($this->uri->segment(3)=='add_customer'){
$this->add_customer();
}
else if($this->uri->segment(3)=='add_post'){
$this->add_post();
}
else{
$this->add_project();
}
}
This is my full controller:
class ADD extends MX_Controller {
public $mname, $tag, $tpl;
function __construct()
{
$this->mname=strtolower(get_class());
$this->tag=strtoupper($this->mname);
}
public function index(){
if($this->uri->segment(3)=='add_customer'){
$this->add_customer();
}
else if($this->uri->segment(3)=='add_post'){
$this->add_post();
}
else{
$this->add_project();
}
}
public function add_project()
{
include APPPATH."language/".LANG.".php";
$this->load->model($this->mname.'/add_project_model');
$model='add_project_model';
$this->$model->index($this->mname);
$a['IsEnabled']=$LANGUAGE['IsEnabled'];
$a['Submit']=$LANGUAGE['Submit'];
$a['Cancel']=$LANGUAGE['Cancel'];
$a['Reset']=$LANGUAGE['Reset'];
$a['Name']=$LANGUAGE['Name'];
$a['SelectCustomer']=$LANGUAGE['SelectCustomer'];
$a['Project Name']=$LANGUAGE['ProjectName'];
$a['Manager']=$LANGUAGE['Manager'];
$a['Customer']=$LANGUAGE['Customer'];
$userGROUP = $this->session->userdata('_userGROUP');
if ($userGROUP=='Administrator')
$a['AddManager']='<button type="button" class="btn btn-warning" onclick="AddNewManager()">+</button>';
else
$a['AddManager']='';
$this->tp->assign($a);
$this->tp->parse('CONTENT', $this->mname.'/add_project.tpl');
}
public function add_customer()
{
include APPPATH."language/".LANG.".php";
$userGROUP = $this->session->userdata('_userGROUP');
if($userGROUP!=='Administrator')
{
show_404('page');
exit;
}
$this->load->model($this->mname.'/add_customer_model');
$model='add_customer_model';
$this->$model->index($this->mname);
$a['IsEnabled']=$LANGUAGE['IsEnabled'];
$a['Submit']=$LANGUAGE['Submit'];
$a['Cancel']=$LANGUAGE['Cancel'];
$a['Reset']=$LANGUAGE['Reset'];
$a['Name']=$LANGUAGE['Name'];
$a['Project Name']=$LANGUAGE['CustomerName'];
$a['Customer Name']=$LANGUAGE['Customer Name'];
$this->tp->assign($a);
$this->tp->parse('CONTENT', $this->mname.'/add_customer.tpl');
}
public function add_post()
{
include APPPATH."language/".LANG.".php";
$userGROUP = $this->session->userdata('_userGROUP');
if($userGROUP=='Engineer')
{
show_404('page');
exit;
}
$this->load->model($this->mname.'/add_post_model');
$model='add_post_model';
$this->$model->index($this->mname);
$a['IsEnabled']=$LANGUAGE['IsEnabled'];
$a['Submit']=$LANGUAGE['Submit'];
$a['Cancel']=$LANGUAGE['Cancel'];
$a['Reset']=$LANGUAGE['Reset'];
$a['Activity Name']=$LANGUAGE['Activity Name'];
$a['SalaryHour']=$LANGUAGE['SalaryHour'];
$this->tp->assign($a);
$this->tp->parse('CONTENT', $this->mname.'/add_post.tpl');
}
}
How can I resolve this problem?

Just Give it a Try, Hope it works :
public function index(){
if($this->uri->segment(3)=='add_customer'){
redirect(base_url().'/Add/add_customer');
//$this->add_customer();
}
else if($this->uri->segment(3)=='add_post'){
redirect(base_url().'/Add/add_post');
//$this->add_post();
}
else{
redirect(base_url().'/Add/add_project');
//$this->add_project();
}
}

Your index function is never reached
This would reach it : http://project.dev/add
By default the following urls hit the appropriate function.
http://project.dev/add/add_customer hit public function add_customer()
http://project.dev/add/add_post hit public function add_post()
If you are getting errors check out the various error in the specific function and make sure you have error reporting turned on

Related

Laravel OBSERVER update process

In SESSObServer
public function updated(SESS $sESS)
{
log::info("data updated");
if ($sESS->wasChanged('is_active')) {
log::info("data updated");
}
}
IN Observer, created(SESS $sESS) function run but update is not run. How can i solve problem ?
I changed my query. Now, this is run.
I didn't use get. I used first()
$sess = SESS::where('sess_id', request('id'))->first();
$sess->save();
Make sure your Observer is registered.
# app/Providers/EventServiceProvider.php
use App\Models\SESS;
use App\Observers\SESSObserver;
class EventServiceProvider extends ServiceProvider
{
public function boot()
{
SESS::observe(SESSObServer::class);
}
}
Make sure you're using the correct classes. The logger's class is Log (capital L)
public function updated(SESS $sESS)
{
Log::info("data updated");
if ($sESS->wasChanged('is_active')) {
Log::info("data updated");
}
}
Alternatively, I think you can still use info().
public function updated(SESS $sESS)
{
info("data updated");
if ($sESS->wasChanged('is_active')) {
info("data updated");
}
}
If you're using apache, make sure the apache user can write to the log file.

how to write Feature Test for -excel document upload check

i'm using https://docs.laravel-excel.com/ for uploading Excel and then display on view
here is my controller
public function import()
{
$rows= Excel::toArray(new ProfitAndLosImport, request()->file('pl'));
return view("pl")->with(compact('rows'));
}
how to write test for checking this process ?
Any help would be much appreciated
i'm using this but it's working
public function testUpload()
{
Excel::fake();
$this->actingAs(factory('App\User')->create());
$testFile = UploadedFile::fake()->create('borrowers.xlsx');
$response =$this->post('pl',['pl'=>$testFile]);
Excel::assertImported('create_terms.xls', function(ProfitAndLosImport $import) {
return true;
});
}

Unable to trigger event(post.customer.login and post.customer.logout) in Opencart 3.0.2.0

I want to set the session after user login in opencart-3.0.2.0
I am new to opencart, I have just created this two files only in the corresponding folder.anything else I need to be done to trigger the event.
I am referring this link to trigger the event in opencart:https://isenselabs.com/posts/opencart2-event-system-tutorial
I have searched a lot on google still no result found.
Code that I am using to trigger event in opencart.
path : admin/controller/module/mymodule.php
Code :
public function install() {
$this->load->model('extension/event');
$this->model_extension_event->addEvent('mymodule', 'pre.admin.store.delete', 'module/mymodule/on_store_delete');
$this->model_extension_event->addEvent('mymodule', 'post.customer.login', 'module/mymodule/post_customer_login_customtoken');
$this->model_extension_event->addEvent('mymodule', 'post.customer.logout', 'module/mymodule/post_customer_logout_function');
}
public function uninstall() {
$this->load->model('extension/event');
$this->model_extension_event->deleteEvent('mymodule');
}
public function on_store_delete($store_id) {
$this->load->model('setting/store');
$store_info = $this->model_setting_store->getStore($store_id);
$admin_mail = $this->config->get('config_email');
mail($admin_mail, "A store has been deleted", "The store " . $store_info['url'] . " was deleted.");
}
}
path : catalog/controller/module/mymodule.php
Code :
<?php
class ControllerModuleMyModule extends Controller {
public function post_customer_login_customtoken() {
$str = 'abcdefghigklmnopqrstuvwxyz';
$shuffled = str_shuffle($str);
$this->session->data['custom_token'] = $shuffled;
}
public function post_customer_logout_function(){
$this->log->write("post_customer_logout_function");
unset($this->session->data['custom_token']);
}
}
That tutorial is for OpenCart 2.0 - 2.1, in OpenCart 2.2 and above Event system has been changed.
For OpenCart 3.0.2.0 instead of:
$this->load->model('extension/event');
// and
$this->model_extension_event->addEvent
use:
$this->load->model('setting/event');
// and
$this->model_setting_event->addEvent
Instead of:
'post.customer.login'
use:
'catalog/controller/account/login/after'
Instead of:
deleteEvent
Use:
deleteEventByCode
So it must be:
admin\controller\extension\module\mymodule.php
public function install(){
$this->load->model('setting/event');
$this->model_setting_event->addEvent('mymodule', 'catalog/controller/account/login/after', 'extension/module/mymodule/after_customer_login_customtoken');
}
public function uninstall(){
$this->load->model('setting/event');
$this->model_setting_event->deleteEventByCode('mymodule');
}
catalog\controller\extension\module\mymodule.php
class ControllerExtensionModuleMyModule extends Controller {
public function after_customer_login_customtoken(){
$this->log->write('test');
}
}

Zend Framework: How to stop dispatch/controller execution?

I have a Zend Framework controller with an editAction().
class WidgetController extends BaseController
{
public function editAction()
{
//code here
}
}
This controller extends a base controller which checks if the user is logged in before allowing the user to edit a record.
class BaseController extends Zend_Controller_Action
{
public function init()
{
if ($this->userNotLoggedIn()) {
return $this->_redirect('/auth/login');
}
}
}
However, now that I am performing an AJAX request, I will be sending a JSON response back, so a redirect will no longer work. I need to stop further controller execution so I can immediately send a response:
class BaseController extends Zend_Controller_Action
{
public function init()
{
if ($this->userNotLoggedIn()) {
if ($this->_request->isXmlHttpRequest()) {
$jsonData = Zend_Json::encode(array('error'=>'You are not logged in!'));
$this->getResponse()
->setHttpResponseCode(401)
->setBody($jsonData)
->setHeader('Content-Type', 'text/json');
//now stop controller execution so that the WidgetController does not continue
} else {
return $this->_redirect('/auth/login');
}
}
}
}
How can I stop controller execution?
I would define the user not being logged in and trying to make an XMLHTTPRequest as an exceptional state and let the error handler deal with it by throwing an exception (which stops dispatching of the current action). That way you are also able to handle other kinds of exceptions that might happen:
class BaseController extends Zend_Controller_Action
{
public function init()
{
if ($this->userNotLoggedIn()) {
if ($this->_request->isXmlHttpRequest()) {
throw new Exception('You are not logged in', 401);
} else {
return $this->_redirect('/auth/login');
}
}
}
}
class ErrorController extends Zend_Controller_Action
{
public function errorAction()
{
$errors = $this->_getParam('error_handler');
$exception = $errors->exception;
if ($this->_request->isXmlHttpRequest()) {
$jsonData = Zend_Json::encode($exception);
$jsonData = Zend_Json::encode(array('error'=> $exception->getMessage()));
$isHttpError = $exception->getCode() > 400 && $exception->getCode();
$code = $isHttpError ? $exception->getCode() : 500;
$this->getResponse()
->setHttpResponseCode($code)
->setBody($jsonData)
->setHeader('Content-Type', 'application/json');
} else {
// Render error view
}
}
}
I can think of many ways to stop the controller at this point in your code.
//now stop controller execution so that the WidgetController does not continue
For one, you can replace that line with this the following:
$this->getResponse()->sendResponse();
exit;
That may not be the cleanest but gets the job done rather nicely. The other option is going to be to change the action of the request in the init and let another action handle it. Replace that line with this:
$this->getRequest()->setActionName('invalid-user');
Because your already inside the dispatcher, it's going to run an action inside your action class whether you want it to or not. Trying to change the request in preDispatch will do nothing to change this dispatch. It's determined at this point to run an action inside your class. So, make an action to handle it.
public function invalidUserAction()
{
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
}
For more information see Zend_Controller_Dispatcher_Standard::dispatch.

MVC3 uri with or without "/" show different response

What is difference between these two paths?
http://www.mydomain.com/testmvc3
http://www.mydomain.com/testmvc3/
I put the code in HomeController:
// GET: /Home/
public ActionResult Index()
{
if (Request.IsAuthenticated)
{
return RedirectToAction("Index", "Member");
}
else
{
return View();
}
}
But only the second link works fine, but the first one still show the Home page.(even it is authenticated) How to make them have the same react?
I found the problem, it was caused by the page cache. To avoid the problem, I modify the code to:
[OutputCache(Duration = 30, VaryByCustom = "Request.IsAuthenticated")]
public ActionResult Index()
{
if (Request.IsAuthenticated)
{
return RedirectToAction("Index", "Member");
}
else
{
return View();
}
}
Now it works.
You will want to leave the trailing slash off of a normal route, otherwise it indicates that there may be url parameters coming into the action.
To enforce this you might want to check out the cleanurl filter that is in MvcCms. Source Code
private bool IsTrailingSlashDirty(ref string path)
{
//we only want a trailing slash on the homepage
if (path.EndsWith("/") && !path.Equals("/"))
{
path = path.TrimEnd(new char[] { '/', '/' });
return true;
}
return false;
}

Resources