How to hook a pay now button to the bottom of WooCommerce Customer Invoice Template? - hook-woocommerce

I am trying to add a Pay Now button to the bottom of the Customer invoice / Order details email that gets sent manually.
I'm getting a fatal error (Too few arguments to function 1 passed and exactly 2 expected) when running this code:
//Add Pay Now button to invoice email
add_action('woocommerce_email_footer', 'rnr_customer_order_invoice_paynow',20,2 );
function rnr_customer_order_invoice_paynow($order, $email) {
if ( $email->id == 'customer_invoice' ) {
$pay_now_url = esc_url( $order->get_checkout_payment_url() );
echo '<a"href=" ' . $pay_now_url . '">Pay Now</a>';
}
}

I figured out why I can't hook into the footer. The woocommerce_email_footer hook only has the $email attribute, not the $order attribute. I hooked into woocommerce_email_after_order_table which has 4 attributes available, including $order.
However this does not answer the original question of how to hook into the bottom of the template.) Perhaps with some global variable to get the $order information?
//Add Pay Now button to invoice email
add_action('woocommerce_email_after_order_table', rnr_customer_order_invoice',20,4 );
function rnr_customer_order_invoice($order, $sent_to_admin, $plain_text, $email )
{
if ( $email->id == 'customer_invoice' ) {
$pay_now_url = esc_url( $order->get_checkout_payment_url() );
echo '<a"href=" ' . $pay_now_url . '">Pay Now</a>';
}
}

Related

How to integrate the element label into the validation error message in ZF2?

I have a form, where the error messages have to be displayed bundled at one place. The default messages are general, so the user sometimes doesn't know, which message is for which form field:
A record matching the input was found
Value is required and can't be empty
The input is not a valid email address...
I could write a custom message for every field, but is much effort and copy&paste.
So, I'd like to display the messages like this:
My element Foo label: A record matching the input was found
My element Bar label: Value is required and can't be empty
My element Buz label: The input is not a valid email address...
How to achieve this?
ZF2 seems not to provide a solution for this requirement. My solution/workaround is to override the Zend\Form\View\Helper\FormElementErrors replacing these lines of the FormElementErrors#render(...) by
$this->prepareMessagesToPrint($messages, $messagesToPrint, $element, $escapeHtml);
and add a method, that process the $messages as desired:
protected function prepareMessagesToPrint($messages, &$messagesToPrint, $element, $escapeHtml) {
foreach ($messages as $nameOrType => $elementOrError) {
if (is_string($elementOrError)) {
$elementLabel = $element->getLabel()
? '<b>' . $this->view->translate($element->getLabel()) . '</b>' . ': '
: null
;
$message = $escapeHtml($elementOrError);
$messagesToPrint[] = $elementLabel ? $elementLabel . $message : $message;
} elseif (is_array($elementOrError)) {
$newElement = $element->get($nameOrType);
$this->prepareMessagesToPrint(
$elementOrError, $messagesToPrint, $newElement, $escapeHtml
);
}
}
}

Phalcon PHP post link with JavaScript confirmation dialog

I am developing a CRUD system in Phalcon PHP (version 1.3.4).
My goal is to create a link (delete row), that asks for confirmation on click (JavaScript confirmation box) and then goes (request type POST) to the link.
So lets say a user clicks on the "delete row" button.
JavaScript confirmation "Are you sure you want to delete this row?"
User clicks "yes"
Webpage does a POST to "/users/delete/1"
I know CakePHP has a function (FormHelper::postLink()) that does exactly that.
I was wondering if Phalcon PHP also had a function like this.
I see three possibilities to achieve what you want. One is to create a macro in Volt template, second is to add a function to your View. Third and closest to - what I understand is your wish - is to extend Phalcons tag helper and this is part I will describe here.
Phalcon has its own Tag helper to allow you to easily create some elements. postLink is not a part that is implemented there, but you can easily achieve it. In my example I have namespace of Application with class of Tag that extends from \Phalcon\Tag. This is my base for this tutorial.
// Tag.php
namespace Application;
class Tag extends \Phalcon\Tag
{
static public function postLink() {
return '<strong>TEST TAG</strong>';
}
}
To force Phalcon DI to use this class, it is necessary to override it's standard declaration from engine by declaring it by hand as a new DI service:
// services.php
$di['tag'] = function() {
return new \Application\Tag();
};
You can test if it is working properly by typing {{ tag.postLink() }} in Volt template or with $this->tag->postLink() if using phtml template.
Now you can fill your Tag::postLink() method with HTML and parameters you wish it will produce:
namespace Application;
class Tag extends \Phalcon\Tag
{
static $forms = [];
static public function postLink($title, $url, $options = array()) {
// random & unique form ID
while ($randId = 'f_' . mt_rand(9000, 999999)) {
if (!isset(self::$forms[$randId])) {
self::$forms[$randId] = true;
break;
}
}
// dialog message
$dialogMessage = isset($options['message']) && $options['message'] ? $options['message'] : 'Are you sure you want to go on?';
$html = <<<HTML
<form action="{$url}" method="post" id="{$randId}">
<!-- maybe not necessary part -->
<input type="hidden" name="confirmed" value="1" />
</form>
{$title}
HTML;
return $html;
}
}
Now you can run it like this:
{{ tag.postLink('delete', '/users/delete/1') }}
{% set formOptions = ['message' : 'Are you sure you want to delete user Kialia Kuliambro?'] %}
{{ tag.postLink('delete', '/users/delete/1', formOptions) }}
{{ tag.postLink('delete', '/users/delete/1', ['message' : 'Are you sure you want to delete user Kialia Kuliambro?']) }}
Have fun extending :)
There's a few ways to implement such behavior in phalcon. Before anything, we need to understand how views and view helpers work in phalcon. And if you pay close attention, you'll notice, both .volt and .phtml have direct access to the DI.
In volt, for example, you can access the flash service, and output its messages by calling:
{{ flash.output() }}
which gets converted to the phtml: <?php echo $this->flash->output(); ?>
Thus my solution focuses on defining a new service in the DI which volt can access. In CakePHP, the syntax for postLink(), looks something like: echo $this->Form->postLink() while the function is actually defined in a class named FormHelper. So my solution will do the same thing, define a class FormHelper, then inject it into the view under the name Form.
Create an app/helpers/ directory.
Update your app/config/config.php file adding a reference to our new directory: 'helpersDir'=> APP_PATH . '/app/helpers/'
Update your app/config/loader.php file adding $config->application->helpersDir to the registered directories.
Create a new file app/helpers/FormHelper.php
Copy-paste the following code into the file:
<?php
use Phalcon\Tag;
class FormHelper extends Tag
{
protected $_lastAction = '';
public function dottedNameToBracketNotation($name)
{
$parts=explode('.',$name);
$first = array_shift($parts);
$name=$first . ($parts ? '[' . implode('][', $parts) . ']' : '');
return $name;
}
protected function flatten(array $data, $separator = '.')
{
$result = [];
$stack = [];
$path = null;
reset($data);
while (!empty($data)) {
$key = key($data);
$element = $data[$key];
unset($data[$key]);
if (is_array($element) && !empty($element)) {
if (!empty($data)) {
$stack[] = [$data, $path];
}
$data = $element;
reset($data);
$path .= $key . $separator;
} else {
$result[$path . $key] = $element;
}
if (empty($data) && !empty($stack)) {
list($data, $path) = array_pop($stack);
reset($data);
}
}
return $result;
}
protected function _confirm($message, $okCode, $cancelCode = '', $options = [])
{
$message = json_encode($message);
$confirm = "if (confirm({$message})) { {$okCode} } {$cancelCode}";
if (isset($options['escape']) && $options['escape'] === false) {
$confirm = $this->h($confirm);
}
return $confirm;
}
public function h($text, $double = true, $charset = 'UTF-8')
{
return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, $charset, $double);
}
protected function _lastAction($url)
{
$action = $url;//Router::url($url, true);
$query = parse_url($action, PHP_URL_QUERY);
$query = $query ? '?' . $query : '';
$this->_lastAction = parse_url($action, PHP_URL_PATH) . $query;
}
public function postLink($title, $url = null, array $options = [])
{
$out='';
$options += ['block' => null, 'confirm' => null];
$requestMethod = 'POST';
if (!empty($options['method'])) {
$requestMethod = strtoupper($options['method']);
unset($options['method']);
}
$confirmMessage = $options['confirm'];
unset($options['confirm']);
$formName = str_replace('.', '', uniqid('post_', true));
$formOptions = [
'name' => $formName,
'style' => 'display:none;',
'method' => 'post',
];
if (isset($options['target'])) {
$formOptions['target'] = $options['target'];
unset($options['target']);
}
$formOptions[0]=$url;
$out.=$this->form($formOptions);
$out .= $this->hiddenField(['_method','value' => $requestMethod]);
$fields = [];
if (isset($options['data']) && is_array($options['data'])) {
foreach ($this->flatten($options['data']) as $key => $value) {
$out .= $this->hiddenField([$this->dottedNameToBracketNotation($key),'value' => $value]);
}
unset($options['data']);
}
$out .= $this->endForm();
//This is currently unsupported
if ($options['block']) {
if ($options['block'] === true) {
$options['block'] = __FUNCTION__;
}
//$this->_View->append($options['block'], $out);
$out = '';
}
unset($options['block']);
$url = '#';
$onClick = 'document.' . $formName . '.submit();';
if ($confirmMessage) {
$options['onclick'] = $this->_confirm($confirmMessage, $onClick, '', $options);
} else {
$options['onclick'] = $onClick . ' ';
}
$options['onclick'] .= 'event.returnValue = false; return false;';
$options[0]=$url;
$options[1]=$title;
$options[2]=false;
$out .= $this->linkTo($options);
return $out;
}
}
Edit your app/config/services.php file and add in:
$di->set('Form',function () {
return new FormHelper();
});
(you could make "Form" lowercase if you want, both work. I made it capital to closer resemble CakePHP's syntax. Do note that Volt is case sensitive when trying to access services but phtml will lowercase it.)
Edit the template you want to test the code on, such as app/views/index/test.volt
Copy-paste the following code into there:
{{ Form.postLink(' Delete','',['confirm':'Are you sure you want to delete #4?','data':['a':['b','c']]]) }}
Alternatively for phtml, use: <?php echo $this->form->postLink(' Delete', '', array('confirm' => 'Are you sure you want to delete #4?', 'data' => array('a' => array('b', 'c')))); ?>
Run it, and watch it work its magic, just render your index/test.volt template by visiting /index/test in your address bar. (Make sure you defined such an action in your index controller)
In terms, of other solutions, you could also use $compiler->addFunction() to make functions available to volt, one at time. The page in the manual gives the example of $compiler->addFunction('shuffle', 'str_shuffle');. You can attempt to override the factoryDefault for "tag" in the DI, and use the helper we already defined which extends tag. So you'd just change it from "form" to "tag" like so: $di->set('tag',function () {return new FormHelper();}); but, as you can see, it won't make the function postLink() available to volt as a function, you'll notice you still need to access it as tag.postLink(). Rather, all the \Phalcon\Tag functions are actually hard-coded into the volt engine. You can see this clearly by viewing the zephir source code of the \Phalcon\Mvc\View\Engine\Volt\Compiler class available over here. For your convenience, and in case the link ever gets broken, I have posted a snippet here which shows the "tag" functions in volt are actually hard-coded into it:
if method_exists(className, method) {
let arrayHelpers = this->_arrayHelpers;
if typeof arrayHelpers != "array" {
let arrayHelpers = [
"link_to": true,
"image": true,
"form": true,
"select": true,
"select_static": true,
"submit_button": true,
"radio_field": true,
"check_field": true,
"file_field": true,
"hidden_field": true,
"password_field": true,
"text_area": true,
"text_field": true,
"email_field": true,
"date_field": true,
"tel_field": true,
"numeric_field": true,
"image_input": true
];
let this->_arrayHelpers = arrayHelpers;
}
if isset arrayHelpers[name] {
return "$this->tag->" . method . "(array(" . arguments . "))";
}
return "$this->tag->" . method . "(" . arguments . ")";
}
So, if you'd like to "hack" in a few more methods by extending the \Phalcon\Tags class, you're out of luck. However, as demonstrated on the volt documentation page, there exists the concept of registering custom extensions to work with volt. The documentation gives the example of: $compiler->addExtension(new PhpFunctionExtension());
Where the source of the class is:
<?php
class PhpFunctionExtension
{
/**
* This method is called on any attempt to compile a function call
*/
public function compileFunction($name, $arguments)
{
if (function_exists($name)) {
return $name . '('. $arguments . ')';
}
}
}
This would allow volt access to any function you'd like, without having to manually register every possible function you could possibly ever need. You can test this by trying to access str_shuffle in volt, like we did before with $compiler->addFunction('shuffle', 'str_shuffle'); but this time without having to register it.
In terms of other solutions, you could also try to integrate CakePHP and PhalconPHP together, and attempt to call CakePHP's view helpers from PhalconPHP, but then you'd run into a problem of CakePHP not understanding your router setup you have configured in Phalcon. But, if you're determined, you could code all the routes and config for CakePHP and run it alongside PhalconPHP, but I'd highly discourage such a desperate workaround. And, finally, if you understand how the function works, and you barely use it, you could get away with just hard-coding the HTML in the first place. Honestly, CakePHP's logic doesn't look so sound to me in the first place because it has to corrupt your HTML document with a form inserted which can bother your layout. I think it would make more sense to generate a form dynamically with JavaScript, if we're using JavaScript already, and append it to the <body> when the button is clicked, then submit the form we just created dynamically. But, you wanted a CakePHP implementation, so I coded it as close to the logic they used as possible. It's not perfect, in terms of supporting all their features, such as block, but it should suit most of your needs.
I can always revise my implementation, but I think it demonstrates how to work with Phalcon pretty well for those migrating from CakePHP.

Unable to print error message in foreach in magento admin

Hi i have added a new mas action in the sales order grid which allow create batch invoices.
For this my controler file is
<?php
class Iclp_Batchupdate_IndexController extends Mage_Adminhtml_Controller_Action
public function batchinvoiceAction ()
{
$already = " already ";
$refererUrl = $this->getRequest()->getServer('HTTP_REFERER');
$this->loadLayout();
$this->renderLayout();
$orderIds = explode(",",$this->getRequest()->getParam('order_ids'));
foreach ($orderIds as $orderIdss) {
$order = Mage::getModel('sales/order')->load($orderIdss);
//echo $orderIdss ."<br/>";
//echo "already ".$order->getStatusLabel();
try
{
if(!$order->canInvoice())
{
echo Mage::getSingleton('core/session')->addError($orderIdss.$already.$order->getStatusLabel());
}
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')->addObject($invoice)->addObject($invoice->getOrder());
$transactionSave->save();
$order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true)->save();
//echo "Invoice are created";
}
catch (Mage_Core_Exception $e) {
}
}
//A Success Message
Mage::getSingleton('core/session')->addSuccess("Some success message");
//A Error Message
Mage::getSingleton('core/session')->addError("Some error message");
//A Info Message (See link below)
Mage::getSingleton('core/session')->addNotice("This is just a FYI message...");
//These lines are required to get it to work
session_write_close();
$this->getResponse()->setRedirect($refererUrl);
}
}
every thing is working fine but the problem is it is not printing the error message in foreach in above code
if(!$order->canInvoice())
{
echo Mage::getSingleton('core/session')->addError($orderIdss.$already.$order->getStatusLabel());
}
but the bottom error message are displayed properly. MOreover if i extend the class with front-action than it also prints the foreach messages. Please suggest where i am doing the mistake
You should add your errors and messages to admintml/session and not to core/session when you are in adminhtml. That should display the message correctly. You shouldn't need session_write_close();. There is also no need to echo the message, that should be handled automatically by Magento after the redirect.
There is also no need to call $this->loadLayout(); and $this->renderLayout(); because you are redirecting at the end.
Finally, regarding the redirect, you should not read the referrer yourself, Magento can to that for you more reliably. Just use the $this->_redirectReferer(); method instead of $this->getResponse()->setRedirect($refererUrl);.

Why i don't see my #replies in conversation view in twitter?

I need to reply to one particular twitter status. I'm using following functions. And I've used Abraham's twitteroauth library in php.
public function replyToTwitterStatus($user_id,$status_id,$twitt_reply,$account_name)
{
$connection= $this->getTwitterConnection($user_id,$account_name);
try{
$responce = $this->postApiData('statuses/update', array('status' => $twitt_reply,'in_reply_to_status_id '=> $status_id),$connection);
}
catch(Exception $e){
echo $message = $e->getMessage();
exit;
}
}
// this function will handle all post requests
// To post/update twitter data
// To post/update twitter data
public function postApiData($request,$params = array(),$connection)
{
if($params == null)
{
$data = $connection->post($request);
}
else
{
$data = $connection->post($request,$params);
}
// Need to check the error code for post method
if($data->errors['0']->code == '88' || $data->errors['0']->message == 'Rate limit exceeded')
{
throw new Exception( 'Sorry for the inconvenience,Please wait for minimum 15 mins. You exceeded the rate limit');
}
else
{
return $data;
}
}
But the issue is that it is not maintaining the conversation view and it is update like normal status for e.g #abraham hello how are you. but that "View conversation" is not coming. Like expanding menu is not coming.
Please do needful
Thanks
You've got an unwanted space in your in_reply_to_status_id key which causes that parameter to be ignored.
This call:
$responce = $this->postApiData('statuses/update', array(
'status' => $twitt_reply,
'in_reply_to_status_id ' => $status_id
), $connection);
should look like this:
$responce = $this->postApiData('statuses/update', array(
'status' => $twitt_reply,
'in_reply_to_status_id' => $status_id
), $connection);
Also, make sure that the $status_id variable is being handled as a string. Although they look like numbers, most ids will be too big to be represented as integers in php, so they'll end up being converted to floating point which isn't going to work.
Lastly, make sure you have include the username of the person you are replying to in the status text. Quoting from the documentation for the in_reply_to_status_id parameter:
Note:: This parameter will be ignored unless the author of the tweet this parameter references is mentioned within the status text. Therefore, you must include #username, where username is the author of the referenced tweet, within the update.

for each element with behat or codeception

I want to test a website which has a dynamic menustructure. I want to loop through all menuitems and run the same series of test on every page. We're talking about 100+ pages that change reguraly.
I would like to do this with either behat or codeception.
Does anybody have an idea about how to do this?
When using Behat with Mink, you can grab your menu items with findAll() and then iterate over it:
/**
* #When /^I run my test series for all menu items$/
*/
public function iRunMyTestSeriesForAllMenuItems() {
$result = TRUE;
$this->getSession()->visit('http://www.example.com/');
$links = $this->getSession()->getPage()->findAll('css', '#menu ul li a');
foreach ($links as $link) {
$url = $link->getAttribute('href');
if (FALSE === $this->yourTestHere($url)) {
$result = FALSE;
}
}
return $result;
}
I had a similar use case where I wanted to visit all pages of a given site map making sure there isn't any dead links. I had the approach to dynamically generate an array of steps which is then returned and processed by Behat. I had to add an artificial step "I print out page" to make sure I can see on the console what page is currently tested.
/**
* #Then /^I should access all pages of site map "([^"]*)"$/
*/
public function iShouldAccessAllPagesOfSiteMap($selector) {
$page = $this->getSession()->getPage();
$locator = sprintf('#%s a', $selector);
$elements = $page->findAll('css', $locator);
$steps = array();
foreach ($elements as $element) {
/** #var \Behat\Mink\Element\NodeElement $element */
$steps[] = new Behat\Behat\Context\Step\When(sprintf('I print out page "%s"', $element->getAttribute('href')));
$steps[] = new Behat\Behat\Context\Step\When(sprintf('I go to "%s"', $element->getAttribute('href')));
$steps[] = new Behat\Behat\Context\Step\Then('the response status code should be 200');
}
return $steps;
}
/**
* #When /^I print out page "([^"]*)"$/
*/
public function iPrintOutThePage($page) {
$string = sprintf('Visiting page ' . $page);
echo "\033[36m -> " . strtr($string, array("\n" => "\n| ")) . "\033[0m\n";
}
Then my scenario looks as follows:
Scenario: my website has no "dead" pages
Given I am on "/examples/site-map/"
Then I should access all pages of site map "c118"
The whole Gist is here https://gist.github.com/fudriot/6028678

Resources