I had modified some part of reorder in parentOrderController, created a variable. Now I want to pass that variable into the order-payment.tpl so that I can check a condition with that. Can someone please help me?
ParentOrderContoller.php(Added Part)
if (Tools::isSubmit('submitPay') && $id_order = (int)Tools::getValue('id_order')) {
//To check the order is in print ready state
$order = new Order((int)$id_order);
$current_order_state = $order->getCurrentOrderState();
$current_order_state_id = $current_order_state->id;
//ends here
//d($current_order_state_id);
// $this->context->cookie->current_order_state_id = $current_order_state->id;
$oldCart = new Cart(Order::getCartIdStatic($id_order, $this->context->customer->id));
$duplication = $oldCart->duplicate();
if (!$duplication || !Validate::isLoadedObject($duplication['cart'])) {
$this->errors[] = Tools::displayError('Sorry. We cannot renew your order.');
} elseif (!$duplication['success']) {
$this->errors[] = Tools::displayError('Some items are no longer available, and we are unable to renew your order.');
} else {
$this->context->cookie->id_cart = $duplication['cart']->id;
$context = $this->context;
$context->cart = $duplication['cart'];
CartRule::autoAddToCart($context);
$this->context->cookie->write();
d(Configuration::get('PS_ORDER_PROCESS_TYPE'));
if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1) {
Tools::redirect('index.php?controller=order-opc');
}
Tools::redirect('index.php?controller=order');
}
}
I want $current_order_state_id to be passed to order-payment.tpl. How to do it?
You should be able to do it with:
$this->context->smarty->assign(array(
'current_order_state_id' => $current_order_state_id
));
Just a side note. If the variable is not always set, in your template check using the:
{if isset($current_order_state_id)}
code
{/if}
Related
I am trying to get a request from the input I just got where if the request input recommendation is No or KIV, it will redirect to home if not it will redirect to another page. But the problem now is that if the recommendation I put is Yes and some other things as No, it will redirect me to home instead of another page. Can someone help me out? Thanks a lot
public function eval(Request $request){
$Evaluation = new evaluation;
$personal_info = new personal_info;
$Evaluation->recommendation = $request->input('recommendation');
$Evaluation->training_schedule = $request->input('training_schedule');
$Evaluation->training_date = $request->input('training_date');
$Evaluation->PortalLogin = $request->input('PortalLogin');
$id = $request->user_id;
$id= personal_info::find($id);
$id->evaluations()->save($Evaluation);
if(($Evaluation->recommendation = $request->input('recommendation')) == 'No' || 'KIV')
return redirect('/home');
else{
return redirect(url('/user/showtest/'.$id->id.'/test) );
}
They syntax of your "if statement" is incorrect. || 'Kiv' this statement is evaluated alone and not against recommendation, so change the code to this way
$recommendation = $Evaluation->recommendation = $request->input('recommendation');
if( $recommendation == 'No' || $recommendation == 'KIV')
return redirect('/home');
else {
return redirect(url('/user/showtest/'.$id->id.'/test) );
}
I'm creating a buy-now button cs-cart add-on. I've created an add-on and I've made the add-to-cart functionality work. But cant redirect it to checkout page. I have used "fn_redirect("checkout")" function for the redirection. And used this function below this:
"fn_add_product_to_cart($_REQUEST['product_data'], $cart, $auth);"
What should I do for redirection?
Edit:
My controller (buy_now.php)
if ($mode == 'add') {
if (empty($auth['user_id']) && Registry::get('settings.General.allow_anonymous_shopping') != 'allow_shopping')
{
return array(CONTROLLER_STATUS_REDIRECT, "auth.login_form?return_url=" . urlencode($_REQUEST['return_url']));
}
// Add to cart button was pressed for single product on advanced list
if (!empty($dispatch_extra)) {
if (empty($_REQUEST['product_data'][$dispatch_extra]['amount'])) {
$_REQUEST['product_data'][$dispatch_extra]['amount'] = 1;
}
foreach ($_REQUEST['product_data'] as $key => $data) {
if ($key != $dispatch_extra && $key != 'custom_files') {
unset($_REQUEST['product_data'][$key]);
}
}
}
$prev_cart_products = empty($cart['products']) ? array() : $cart['products'];
fn_add_product_to_cart($_REQUEST['product_data'], $cart, $auth);
fn_save_cart_content($cart, $auth['user_id']);
$previous_state = md5(serialize($cart['products']));
$cart['change_cart_products'] = true;
fn_calculate_cart_content($cart, $auth, 'S', true, 'F', true);
if (md5(serialize($cart['products'])) != $previous_state && empty($cart['skip_notification'])) {
$product_cnt = 0;
$added_products = array();
if (!empty($added_products)) {
Registry::get('view')->assign('added_products', $added_products);
if (Registry::get('config.tweaks.disable_dhtml') && Registry::get('config.tweaks.redirect_to_cart')) {
Registry::get('view')->assign('continue_url', (!empty($_REQUEST['redirect_url']) && empty($_REQUEST['appearance']['details_page'])) ? $_REQUEST['redirect_url'] : $_SESSION['continue_url']);
}
fn_redirect(Registry::get('config.https_location') . "/checkout");
// $msg = Registry::get('view')->fetch('views/checkout/components/product_notification.tpl');
//fn_set_notification('I', __($product_cnt > 1 ? 'products_added_to_cart' : 'product_added_to_cart'), $msg, 'I');
$cart['recalculate'] = true;
} else {
fn_set_notification('N', __('notice'), __('product_in_cart'));
}
}
unset($cart['skip_notification']);
$_suffix = '.checkout';
}
`
hook template : add_to_cart.post.tpl
{$id = "buy_now_{$product.product_id}"}
<button id="opener_{$id}" name="dispatch[buy_now.add..{$product.product_id}]" class=" vs-button buynow_btn_">Buy Now</button>
I'd consider putting your fn_redirect("checkout") code into an if/else statement to see what's happening with it.
If you have this code:
fn_add_product_to_cart($_REQUEST['product_data'], $cart, $auth);
Then surely you can put the redirection to the checkout page underneath it?
$redirect_url = "http://testcheckout.com?test=test"; //change this!
$errorMessage = "I should have redirected already....";
if (!empty($redirect_url)) {
//if it's not empty then it should redirect.
fn_redirect($redirect_url);
//Then put a die statement in here just to check it's not executing
//anything else and you can see if the redirect has a problem:
die(print_r($errorMessage, true ));
}
else {
//otherwise there is a problem with the supplied redirect url (empty)
die(print_r($redirect_url, true ));
}
I'd also take a look at this page which might help more:
http://forum.cs-cart.com/topic/6873-direct-buy-button/
Hope that helps!
I'd like some help please, if its possible.
I have created two functions in order to display some messages when is set a $_GET after a redirect.Here's the code:
function display(){
if(isset($_GET['cnf_upd']) && $_GET['cnf_upd'] == '1'){
$value = "The update was successful!";
$type = "confirm";
construct_the_div($value, $type);
}
if(isset($_GET['err_upd']) && $_GET['err_upd'] == '1'){
$value = "The Update failed.";
$type = "error";
construct_the_div($value, $type);
}
if(isset($_GET['cnf_del']) && $_GET['cnf_del'] == '1'){
$value = "Deleted completely.";
$type = "confirm";
construct_the_div($value, $type);
}
if(isset($_GET['err_del']) && $_GET['err_del'] == '1'){
$value = "Unable to delete.";
$type = "error";
construct_the_div($value, $type);
}
}
function construct_the_div($value, $type){
// creating a div to display the message results
$div = "<div class=\"{$type}Msg\">\n";
$div .= "<p>{$value}</p>\n";
$div .= "</div><!-- end of {$type}Msg -->\n";
echo $div;
}
What I'd like to make is to try to improve the display function, as it gets longer and longer, so that there whould be only one (or two at most) if statement(s) if possible. So the value of the GET will be dynamicly inside the if condition and also if it has the preffix 'cnf_' it wil be a 'confirmMsg' and if it has the preffix 'err_' it wil be a 'errorMsg'.
Is it possible to make something like this???
function display() {
$messages = array(
'cnf_upd' => 'The update was successful!',
'cnf_err' => 'The Update failed.!',
// ...
// add all error and confirm there
// ...
);
foreach($_GET as $key => $value) {
if(strpos($key, 'cnf_')===0) {
$type = 'confirm';
$value = isset($messages[$key])
? $messages[$key]
: $key;
construct_the_div($value, $type);
}
if(strpos($key, 'err_')===0) {
$type = 'error';
$value = isset($messages[$key])
? $messages[$key]
: $key;
construct_the_div($value, $type);
}
}
}
The approach is not correct, it seems that only one message should occur at once (there cannot be "deleted completely" and "unable to delete" at once).
Try construct the parameters this way: ?msg=upd&msgType=cnf
function display(){
if (isset($_GET['msg']) && isset($_GET['msgType']))
{
$messages = array('cnf_upd'=>'The update was successful!',
'err_upd'=>'The update failed!',
'cnf_del'=>'The deletion was successful!',
'cnf_upd'=>'The deletion failed!',
);
if (isset($messages[$_GET['msgType'].'_'.$_GET['msg']))
construct_the_div($messages[$_GET['msgType'].'_'.$_GET['msg']], htmlspecialchars($_GET['msgType']));
}
there is still much to improve, but for start this is cleaner and safer.
I'm going to propose a different solution. Instead of setting different parameters in $_GET based on the message to be sent, set one parameter and parse its value.
// Start by setting integer constants:
define(CNF_UPD, 1);
define(ERR_UPD, 2);
define(CNF_DEL, 3);
define(ERR_DEL, 4);
Then when you set the value un $_GET, use the constant:
// Build the URL with a deletion error...
header("Location: http://example.com/script.php?msg=" . ERR_DEL);
Finally, use a switch to parse them
if (isset($_GET['msg'])) {
switch ($_GET['msg']) {
case CNF_UPD:
// Updated...
break;
case ERR_UPD:
// failed...
break;
// etc...
default:
// invalid code.
}
}
If you use a pattern of confirm/error/confirm/error for your integer constants, you can determine which it is by taking $_GET['msg'] % 2. Odd numbers are confirmations, evens are errors. There are of course many other ways you could lay this out, I just happen to have typed them in the alternating order you used. You could also do positive integers for confirmations and negatives for errors, for example.
$type = $_GET['msg'] % 2 == 1 ? $confirm : $error;
This is easily expanded to use multiple messages as well. Since they are integer values, you can safely construct a comma-separated list and explode() them when received.
$messages = implode(array(ERR_DEL,CNF_UPD));
header("Location: http://example.com/script.php?msg=$messages");
Unless you can somehow generate $value and $type based on the $_GET parameter (which I can't see how you would do), you could do something like:
$messages = array();
$messages[] = array('id' => 'cnf_upd', 'value' => 'The update was successful!', 'type' => 'Confirm');
$messages[] = array('id' => 'err_upd', 'value' => 'The Update failed.', 'type' => 'error');
...
foreach ($messages as $message) {
if(isset($_GET[$message['id']]) && $_GET[$message['id']] == '1'){
construct_the_div($message['value'], $message['type']);
}
}
When I access the wrong function in my controller, a 404 error page is working well. But, when i access url like 'http://example.com/model/detail/116', which 116 is wrong number [are not in the database], my 404 error page not working.
I have this code in my controller:
public function detail()
{
$id['id_galeri'] = $this->uri->segment(3);
$detail = $this->app_model->getSelectedData("tbl_galeri",$id);
foreach($detail->result() as $d)
{
$bc['jdl'] = "View";
$bc['id_galeri'] = $d->id_galeri;
$bc['nama'] = $d->nama;
$bc['foto'] = $d->foto;
$bc['deskripsi'] = $d->deskripsi;
$bc['stts_input'] = "deskripsi";
}
if($this->uri->segment(3) == '' && $id['id_galeri'] == FALSE)
{
$segment_url = 0;
}else{
if(!is_numeric($this->uri->segment(3)) || !is_string($this->uri->segment(3))){
redirect('404');
}else{
$segment_url = $this->uri->segment(3);
}
}
$this->load->view('frontend/global/bg_top');
$this->load->view('frontend/page/bg_view_model',$bc);
$this->load->view('frontend/global/bg_footer');
}
Sorry for my bad english, please help :-)
Thank you..
Instead of:
redirect('404');
try using CodeIgniter's native:
show_404('page');
EDIT
Try this code, a bit cleaned up and the checks are done before they're saved for views use.
public function detail()
{
$id['id_galeri'] = $this->uri->segment(3);
// Check if the supplied ID is numeric in the first place
if ( ! is_numeric($id['id_galeri']))
{
show_404($this->uri->uri_string());
}
// Get the data
$detail = $this->app_model->getSelectedData("tbl_galeri",$id);
// Check if any records returned
if (count($detail->result()) === 0)
{
show_404($this->uri->uri_string());
}
foreach($detail->result() as $d)
{
$bc['jdl'] = "View";
$bc['id_galeri'] = $d->id_galeri;
$bc['nama'] = $d->nama;
$bc['foto'] = $d->foto;
$bc['deskripsi'] = $d->deskripsi;
$bc['stts_input'] = "deskripsi";
}
/**
* Here do whatever you want with the $segment_url which doesn't seem to be
* used in your code
*/
$this->load->view('frontend/global/bg_top');
$this->load->view('frontend/page/bg_view_model',$bc);
$this->load->view('frontend/global/bg_footer');
}
I am working with SilverStripe, and I am working on making a newspage.
I use the DataObjectAsPage Module( http://www.ssbits.com/tutorials/2012/dataobject-as-pages-the-module/ ), I got it working when I use the admin to publish newsitems.
Now I want to use the DataObjectManager Module instead of the admin module to manage my news items. But this is where the problem exists. Everything works fine in draft mode, I can make a new newsitem and it shows up in draft. But when I want to publish a newsitem, it won't show up in the live or published mode.
I'm using the following tables:
-Dataobjectaspage table,
-Dataobjectaspage_live table,
-NewsArticle table,
-NewsArticle_Live table
The Articles have been inserted while publishing in the Dataobjectaspage table and in the NewsArticle table... But not in the _Live tables...
Seems the doPublish() function hasn't been used while 'Publishing'.
So I'm trying the use the following:
function onAfterWrite() {
parent::onAfterWrite();
DataObjectAsPage::doPublish();
}
But when I use this, it gets an error:
here is this picture
It seems to be in a loop....
I've got the NewsArticle.php file where I use this function:
function onAfterWrite() {
parent::onAfterWrite();
DataObjectAsPage::doPublish();
}
This function calls the DataObjectAsPage.php file and uses this code:
function doPublish() {
if (!$this->canPublish()) return false;
$original = Versioned::get_one_by_stage("DataObjectAsPage", "Live", "\"DataObjectAsPage\".\"ID\" = $this->ID");
if(!$original) $original = new DataObjectAsPage();
// Handle activities undertaken by decorators
$this->invokeWithExtensions('onBeforePublish', $original);
$this->Status = "Published";
//$this->PublishedByID = Member::currentUser()->ID;
$this->write();
$this->publish("Stage", "Live");
// Handle activities undertaken by decorators
$this->invokeWithExtensions('onAfterPublish', $original);
return true;
}
And then it goes to DataObject.php file and uses the write function ():
public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false) {
$firstWrite = false;
$this->brokenOnWrite = true;
$isNewRecord = false;
if(self::get_validation_enabled()) {
$valid = $this->validate();
if(!$valid->valid()) {
// Used by DODs to clean up after themselves, eg, Versioned
$this->extend('onAfterSkippedWrite');
throw new ValidationException($valid, "Validation error writing a $this->class object: " . $valid->message() . ". Object not written.", E_USER_WARNING);
return false;
}
}
$this->onBeforeWrite();
if($this->brokenOnWrite) {
user_error("$this->class has a broken onBeforeWrite() function. Make sure that you call parent::onBeforeWrite().", E_USER_ERROR);
}
// New record = everything has changed
if(($this->ID && is_numeric($this->ID)) && !$forceInsert) {
$dbCommand = 'update';
// Update the changed array with references to changed obj-fields
foreach($this->record as $k => $v) {
if(is_object($v) && method_exists($v, 'isChanged') && $v->isChanged()) {
$this->changed[$k] = true;
}
}
} else{
$dbCommand = 'insert';
$this->changed = array();
foreach($this->record as $k => $v) {
$this->changed[$k] = 2;
}
$firstWrite = true;
}
// No changes made
if($this->changed) {
foreach($this->getClassAncestry() as $ancestor) {
if(self::has_own_table($ancestor))
$ancestry[] = $ancestor;
}
// Look for some changes to make
if(!$forceInsert) unset($this->changed['ID']);
$hasChanges = false;
foreach($this->changed as $fieldName => $changed) {
if($changed) {
$hasChanges = true;
break;
}
}
if($hasChanges || $forceWrite || !$this->record['ID']) {
// New records have their insert into the base data table done first, so that they can pass the
// generated primary key on to the rest of the manipulation
$baseTable = $ancestry[0];
if((!isset($this->record['ID']) || !$this->record['ID']) && isset($ancestry[0])) {
DB::query("INSERT INTO \"{$baseTable}\" (\"Created\") VALUES (" . DB::getConn()->now() . ")");
$this->record['ID'] = DB::getGeneratedID($baseTable);
$this->changed['ID'] = 2;
$isNewRecord = true;
}
// Divvy up field saving into a number of database manipulations
$manipulation = array();
if(isset($ancestry) && is_array($ancestry)) {
foreach($ancestry as $idx => $class) {
$classSingleton = singleton($class);
foreach($this->record as $fieldName => $fieldValue) {
if(isset($this->changed[$fieldName]) && $this->changed[$fieldName] && $fieldType = $classSingleton->hasOwnTableDatabaseField($fieldName)) {
$fieldObj = $this->dbObject($fieldName);
if(!isset($manipulation[$class])) $manipulation[$class] = array();
// if database column doesn't correlate to a DBField instance...
if(!$fieldObj) {
$fieldObj = DBField::create('Varchar', $this->record[$fieldName], $fieldName);
}
// Both CompositeDBFields and regular fields need to be repopulated
$fieldObj->setValue($this->record[$fieldName], $this->record);
if($class != $baseTable || $fieldName!='ID')
$fieldObj->writeToManipulation($manipulation[$class]);
}
}
// Add the class name to the base object
if($idx == 0) {
$manipulation[$class]['fields']["LastEdited"] = "'".SS_Datetime::now()->Rfc2822()."'";
if($dbCommand == 'insert') {
$manipulation[$class]['fields']["Created"] = "'".SS_Datetime::now()->Rfc2822()."'";
//echo "<li>$this->class - " .get_class($this);
$manipulation[$class]['fields']["ClassName"] = "'$this->class'";
}
}
// In cases where there are no fields, this 'stub' will get picked up on
if(self::has_own_table($class)) {
$manipulation[$class]['command'] = $dbCommand;
$manipulation[$class]['id'] = $this->record['ID'];
} else {
unset($manipulation[$class]);
}
}
}
$this->extend('augmentWrite', $manipulation);
// New records have their insert into the base data table done first, so that they can pass the
// generated ID on to the rest of the manipulation
if(isset($isNewRecord) && $isNewRecord && isset($manipulation[$baseTable])) {
$manipulation[$baseTable]['command'] = 'update';
}
DB::manipulate($manipulation);
if(isset($isNewRecord) && $isNewRecord) {
DataObjectLog::addedObject($this);
} else {
DataObjectLog::changedObject($this);
}
$this->onAfterWrite();
$this->changed = null;
} elseif ( $showDebug ) {
echo "<b>Debug:</b> no changes for DataObject<br />";
// Used by DODs to clean up after themselves, eg, Versioned
$this->extend('onAfterSkippedWrite');
}
// Clears the cache for this object so get_one returns the correct object.
$this->flushCache();
if(!isset($this->record['Created'])) {
$this->record['Created'] = SS_Datetime::now()->Rfc2822();
}
$this->record['LastEdited'] = SS_Datetime::now()->Rfc2822();
} else {
// Used by DODs to clean up after themselves, eg, Versioned
$this->extend('onAfterSkippedWrite');
}
// Write ComponentSets as necessary
if($writeComponents) {
$this->writeComponents(true);
}
return $this->record['ID'];
}
Look at the $this->onAfterWrite();
It probably goes to my own function on NewsArticle.php and there starts the loop! I'm not sure though, so i could need some help!!
Does anyone knows how to use the doPublish() function?
The reason that is happening is that in the DataObjectAsPage::publish() method, it is calling ->write() - line 11 of your 3rd code sample.
So what happens is it calls ->write(), at the end of ->write() your onAfterWrite() method is called, which calls publish(), which calls write() again.
If you remove the onAfterWrite() function that you've added, it should work as expected.
The doPublish() method on DataObjectAsPage will take care of publishing from Stage to Live for you.