Magento 1.9 GET parameters in product view - magento

I have an observer action setup, that checks if a product page is loaded. If so, it calls a custom help that deals with all of the GET paremeters. It used to work for over 4 years and have suddenly stopped (the only thing that changed on the 3rd party's side is the naming of those parameters).
Here is the observer action:
public function productView($observer) {
/*#var $block Mage_Core_Block_Abstract*/
$block = $observer->getEvent()->getBlock();
if ($block && $this->getProduct()){
if ($block->getModuleName() == 'Mage_Catalog'){
$productId = $this->getProduct()->getEntityId();
//If params exist - save
if ($this->ParamsHelper()->saveParams($productId)){
//code omitted
}
}
}
}
Here is the helper's action:
public function saveParams($productId) {
if (is_numeric($productId)){
$params = Mage::app()->getRequest()->getParams();
if (!empty($params['image']) && !empty($params['config'])){
//never gets here
return true;
}
}
return false;
}
If I try to var_dump the $params, I get the following array which only includes product_id:
array(1) { ["id"]=> string(3) "664" }
Expected result is to be able to access all the GET parameters passed via url in product view.
Any help or guidance is much appreciated.
EDIT
Product URLs are similar to product names, like f.e.:
domain.com/red-jacket
In a perfect case, I would expect to get parameters passed like following:
domain.com/red-jacket?param1=aaa&param2=bbb

Not sure whats the exact problem is ... but for domain.com/red-jacket?param1=aaa&param2=bbb you can get parameters in this way:
$params = Mage::app()->getRequest()->getParams();
$param1 = $params['param1']
or
$param1 = Mage::app()->getRequest()->getParam('param1');

//code for get parameters in view page.
$arrParams = Mage::app()->getRequest()->getParams();
echo "Get Parameter"; echo '<pre>', print_r($arrParams);

Related

Magento OPC Observer redirect

I'm struggling with a special little problem related to the redirect out of some Magento observer.
I wrote an extension and put an observer to the "checkout_submit_all_after" event, which works out just fine. My little extension automatically creates an invoice and sets the order status to processing, once the payment method is "Invoice". Unfortunately the redirect after submitting an order in the one page checkout doesn't work anymore. It always redirects to "checkout/cart" instead of "checkout/onepage/success".
Someone any ideas what I'm doing wrong?
Here's my code:
class Shostra_AutoInvoice_Model_Order_Observer
{
public function __construct()
{
}
public function auto_create_invoice($observer)
{
$order = $observer->getEvent()->getOrder();
if (!$order->hasInvoices()) {
$payment = $order->getPayment()->getMethodInstance()->getTitle();
Mage::log("payment method: " . $payment);
if($payment=="Rechnung"){
Mage::log("autocreating invoice");
$invoice = $order->prepareInvoice();
$invoice->register();
$invoice->pay();
$invoice->save();
$order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true)->save();
Mage::log("invoice created and saved");
}
$this->addComment('Order automatically set to paid.');
} else {
$this->addComment('no invoices found.');
}
$response = $observer->getResponse();
$response->setRedirect(Mage::getUrl('checkout/onepage/success'));
Mage::getSingleton('checkout/session')->setNoCartRedirect(true);
}
}
Thanks a lot!
Why don't you try sales_order_save_after event and try saving it, so no issues with redirection manually as Magento will take its own course,
you can refer to this link for more explanation
http://inchoo.net/magento/magento-orders/automatically-invoice-ship-complete-order-in-magento/

Loading page dynamically from database via id in controller

I am trying to load a page dynamically based on the database results however I have no idea how to implement this into codeigniter.
I have got a controller:
function history()
{
//here is code that gets all rows in database where uid = myid
}
Now in the view for this controller I would like to have a link for each of these rows that will open say website.com/page/history?fid=myuniquestring however where I am getting is stuck is how exactly I can load up this page and have the controller get the string. And then do a database query and load a different view if the string exsists, and also retrieve that string.
So something like:
function history$somestring()
{
if($somestring){
//I will load a different view and pass $somestring into it
} else {
//here is code that gets all rows in database where uid = myid
}
}
What I don't understand is how I can detect if $somestring is at the end of the url for this controller and then be able to work with it if it exists.
Any help/advice greatly appreciated.
For example, if your url is :
http://base_url/controller/history/1
Say, 1 be the id, then you retrieve the id as follows:
function history(){
if( $this->uri->segment(3) ){ #if you get an id in the third segment of the url
// load your page here
$id = $this->uri->segment(3); #get the id from the url and load the page
}else{
//here is code that gets all rows in database where uid = myid and load the listing view
}
}
You should generate urls like website.com/page/history/myuniquestring and then declare controller action as:
function history($somestring)
{
if($somestring){
//I will load a different view and pass $somestring into it
} else {
//here is code that gets all rows in database where uid = myid
}
}
There are a lot of ways you can just expect this from your URI segments, I'm going to give a very generic example. Below, we have a controller function that takes two optional arguments from the given URI, a string, and an ID:
public function history($string = NULL, $uid = NULL)
{
$viewData = array('uid' => NULL, 'string' => NULL);
$viewName = 'default';
if ($string !== NULL) {
$vieData['string'] = $string;
$viewName = 'test_one';
}
if ($uid !== NULL) {
$viewData['uid'] = $uid;
}
$this->load->view($viewName, $viewData);
}
The actual URL would be something like:
example.com/history/somestring/123
You then know clearly both in your controller and view which, if any were set (perhaps you need to load a model and do a query if a string is passed, etc.
You could also do this in an if / else if / else block if that made more sense, I couldn't quite tell what you were trying to put together from your example. Just be careful to deal with none, one or both values being passed.
The more efficient version of that function is:
public function history($string = NULL, $uid = NULL)
{
if ($string !== NULL):
$viewName = 'test_one';
// load a model? do a query?
else:
$viewName = 'default';
endif;
// Make sure to also deal with neither being set - this is just example code
$this->load->view($viewName, array('string' => $string, 'uid' => $uid));
}
The expanded version just does a simpler job at illustrating how segments work. You can also examine the given URI directly using the CI URI Class (segment() being the most common method). Using that to see if a given segment was passed, you don't have to set default arguments in the controller method.
As I said, a bunch of ways of going about it :)

Redirect to show_404 in Codeigniter from a partial view

I am using the HMVC pattern in CodeIgniter. I have a controller that loads 2 modules via modules::run() function and a parameter is passed to each module.
If either module cannot match the passed paramter I want to call show_404(). It works, but it loads the full HTML of the error page within my existing template so the HTML breaks and looks terrible. I think I want it to redirect to the error page so it doesn't run the 2nd module. Is there some way to do that and not change the URL?
Is it possible to just redirect to show_404() from the module without changing the URL?
Here is an over simplified example of what's going on:
www.example.com/users/profile/usernamehere
The url calls this function in the users controller:
function profile($username)
{
echo modules::run('user/details', $username);
echo modules::run('user/friends', $username);
}
Which run these modules, which find out if user exists or not:
function details($username)
{
$details = lookup_user($username);
if($details == 'User Not Found')
show_404(); // This seems to display within the template when what I want is for it to redirect
else
$this->load->view('details', $details);
}
function friends($username)
{
$details = lookup_user($username);
if($friends == 'User Not Found')
show_404(); // Redundant, I know, just added for this example
else
$this->load->view('friends', $friends);
}
I imagine there is just a better way to go at it, but I am not seeing it. Any ideas?
You could throw an exception if there was an error in a submodule and catch this in your controller where you would do show_404() then.
Controller:
function profile($username)
{
try{
$out = modules::run('user/details', $username);
$out .= modules::run('user/friends', $username);
echo $out;
}
catch(Exception $e){
show_404();
}
}
Submodule:
function details($username)
{
$details = lookup_user($username);
if($details == 'User Not Found')
throw new Exception();
else
// Added third parameter as true to be able to return the data, instead of outputting it directly.
return $this->load->view('details', $details,true);
}
function friends($username)
{
$details = lookup_user($username);
if($friends == 'User Not Found')
throw new Exception();
else
return $this->load->view('friends', $friends,true);
}
You can use this function to redirect 404 not found page.
if ( ! file_exists('application/search/'.$page.'.php')) {
show_404(); // redirect to 404 page
}
its very simple , i solved the problem
please controler name's first letter must be capital e.g
A controller with
pages should be Pages
and also save cotroler file with same name Pages.php not pages.php
also same for model class
enjoy

CodeIgniter - dynamic pages - default controller url

edit
my solution in routes.php:
$route['news'] = 'news_controller';
$route['gallery'] = 'gallery_controller';
$route['(:any)'] = 'sites/$1';
and in my site conroller:
function index($site_id = '') {
//sanitize $site_id.
$this->site = $this->sites_model->get_site($site_id);
//etc.
}
THX to YAN
question:
so i wrote a little CMS with CodeIgniter. The admin can create sites. the site opens automatically when the segment of the url is like one in the DB. eg mysite.com/sites/about will call the "About" site. this works fine.
now i got a problem with my URL. i want this url
http://www.mysite.com/sites/about
turns to this:
http://www.mysite.com/about
the problem is, that i cannot use the routes.php and set wildcards for each site. (because they are dynamic and i dont know wich site the customer will create - and i dont want to edit the routes.php file for each site he will create - this should be done automatically)
the problem is i got other fix controllers too, like news, gallery or contact:
mysite.com/news, mysite.com/gallery, ...they work fine
so here is my Site Controller:
class Sites extends Public_Controller {
public $site;
public $url_segment;
public function _remap($method)
{
$this->url_segment = $this->uri->segment(2);
$this->load->model('sites_model');
$this->site = $this->sites_model->get_site($this->url_segment);
if($this->site !== FALSE)
{
$this->show_site($this->site);
}
else
{
show_404($this->url_segment);
}
}
public function show_site($data)
{
$this->template->set('site', FALSE);
$this->template->set('site_title', $data['name']);
$this->template->set('content',$data['content']);
$this->template->load('public/template','sites/sites_view', $data);
}}
and this is the Site_model who checks the database...if the url_segment fits the title in the DB:
class Sites_model extends CI_Model {
public function get_site($site_url)
{
if($site_url != ""){
$this->db->where('name', $site_url);
$query = $this->db->get('sites', 1);
if($query->num_rows() > 0){
return $query->row_array();
}
else
{
return FALSE;
}
}else{
return FALSE;
}
} }
i think i need something who checks if the controller exists (the first segment of the url) when not call the Site controller and check if the site is in the DB and when this is false then call 404.
any suggestions how this can be solved?
btw: sry for my english
regards GN
You can handle routes.php in the following way, just keep the (:any) value last:
$route['news'] = 'news_controller';
$route['gallery'] = 'gallery_controller';
$route['(:any)'] = 'sites/$1';
In your sites controller route to the specific site using the data from the URL.
function index($site_id = '') {
//sanitize $site_id.
$this->site = $this->sites_model->get_site($site_id);
//etc.
}
I am having trouble understanding the full intent of the question, but, from what I can tell, don't you simply need to add:
if ($this->uri->segment(1) != 'sites')
... // handle malformed URL

CodeIgniter - showing original URL of index function?

I'm not sure if I'm approaching this fundamentally wrong or if I'm just missing something.
I have a controller and within it an index function that is, obviously, the default loaded when that controller is called:
function index($showMessage = false) {
$currentEmployee = $this->getCurrentEmployee();
$data['currentEmp'] = $currentEmployee;
$data['callList'] = $currentEmployee->getDirectReports();
$data['showMessage'] = $showMessage;
$this->load->view('main', $data);
}
I have another function within that controller that does a bulk update. After the updates are complete, I want the original page to show again with the message showing, so I tried this:
/**
* Will save all employee information and return to the call sheet page
*/
function bulkSave() {
//update each employee
for ($x = 0; $x < sizeof($_POST['id']); $x++) {
$success = Employee::updateEmployeeManualData($_POST['id'][$x], $_POST['ext'][$x], $_POST['pager'][$x], $_POST['cell'][$x], $_POST['other'][$x], $_POST['notes'][$x]);
}
$this->index($success);
}
What is happening is that the original page is accessed using:
localhost/myApp/myController
after the bulk update it is showing as:
localhost/myApp/myController/bulkSave
when I really want it to show the url as the index page again, meaning that the user never really sees the /bulkSave portion of the URL. This would also mean that if the user were to refresh the page it would call the index() function in the controller and not the bulkSave() function.
Thanks in advance.
Is this possible?
You are calling your index() funciton directly, within bulkUpdate() hence the uri does not change back to index because you are not making a new server request, you are just navigating within your controller class.
I usually use the same Controller function for tasks like this, directing traffic based on whether or not $_POST data has been passed or not like this...
function index() {
if($_POST) {
//process posted data
for ($x = 0; $x < sizeof($_POST['id']); $x++) {
$data['showMessage'] = Employee::updateEmployeeManualData($_POST['id'][$x], $_POST['ext'][$x], $_POST['pager'][$x], $_POST['cell'][$x], $_POST['other'][$x], $_POST['notes'][$x]);
}
}
else {
//show page normally
$data['showMessage'] = FALSE;
}
//continue to load page
$currentEmployee = $this->getCurrentEmployee();
$data['currentEmp'] = $currentEmployee;
$data['callList'] = $currentEmployee->getDirectReports();
$this->load->view('main', $data);
}
Then if it is a form that you are submitting, just point the form at itself in your view like this...
<?= form_open($this->uri->uri_string()) ?>
This points the form back at index, and because you are posting form data via $_POST it will process the data.
I usually do a redirect to the previous page as it prevent users to refresh (and submit twice) their data.
You can use the redirect() helper function of CI.
http://codeigniter.com/user_guide/helpers/url_helper.html (at the bottom)

Resources