How can I get Current date in Magento email template?
{{var dateAndTime}} doesn't work. I need to get current date in which the email is sent.
You have 2 options.
Option 1. is to rewrite the method that sends the e-mail and pass the current date as a parameter.
Let's say for example that you want to show the date in the order e-mail.
For that you will need to rewrite the Mage_Sales_Model_Order::sendNewOrderEmail method.
You need to change this:
$mailer->setTemplateParams(array(
'order' => $this,
'billing' => $this->getBillingAddress(),
'payment_html' => $paymentBlockHtml
)
);
To this:
$mailer->setTemplateParams(array(
'order' => $this,
'billing' => $this->getBillingAddress(),
'payment_html' => $paymentBlockHtml,
'dateAndTime' => Mage::getModel('core/date')->date('Y-m-d H:i:s'), //change format as needed.
)
);
Then you will be able to use {{var dateAndTime}} in your new order email template.
This is handy if you want to use your date and time in only one template.
If you want a more general case you need to create your own directive see option 2.
Option 2 creating your own {{}} directive.
Let's say that you want in every e-mail to use {{dateAndTime}} to print to current date and time.
You need to rewrite the class Mage_Widget_Model_Template_Filter and add a new method to it.
See this detailed explanation about how to do it.
Your new method should look like this:
public function dateAndTimeDirective($construction) {
return Mage::getModel('core/date')->date('Y-m-d H:i:s');
}
You can even take it up a notch and be able to pass the date format as a parameter like this:
{{dateAndTime format="Y-m-d"}}
in this case your method that handles the directive should look like this:
public function dateAndTimeDirective($construction) {
$params = $this->_getIncludeParameters($construction[2]);
$format = isset($params['format']) ? $params['format'] : 'Y-m-d H:i:s'
return Mage::getModel('core/date')->date($format);
}
Go to your email template from admin panel. Use block directive as follows
current date is :
{{block type='core/template' area='frontend' template='page/html/date.phtml'}}
Now create a new file date.phtml in your template as follows
app/design/frontend/yourtheme/yourtemplate/page/html/date.phtml
Add following code in php tags (use php date function and echo current date i.e date('d-m-Y'))
<pre><code>
$date = date('d-m-Y');
echo $date;
</code></pre>
Hope this helps!
Related
This is the problem:
The name associated with the email shows up as "Example"
In config/mail.php
set from property as:
'from' => ['address' => 'someemail#example.com', 'name' => 'Firstname Lastname']
Here, address should be the one that you want to display in from email and name should be the one what you want to display in from name.
P.S. This will be a default email setting for each email you send.
If you need to use the Name as a variable through code, you can also call the function from() as follows (copying from Brad Ahrens answer below which I think is good to mention here):
return $this
->from($address = 'noreply#example.com', $name = 'Sender name')
->subject('Here is my subject')
->view('emails.view');
You can use
Mail::send('emails.welcome', $data, function($message)
{
$message->from('us#example.com', 'Laravel');
$message->to('foo#example.com')->cc('bar#example.com');
});
Reference - https://laravel.com/docs/5.0/mail
A better way would be to add the variable names and values in the .env file.
Example:
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=example#example.com
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls
MAIL_FROM_NAME="My Name"
MAIL_FROM_ADDRESS=support#example.com
Notice the last two lines. Those will correlate with the from name and from email fields within the Email that is sent.
In the case of google SMTP, the from address won't change even if you give this in the mail class.
This is due to google mail's policy, and not a Laravel issue.
Thought I will share it here.
For anyone who is using Laravel 5.8 and landed on this question, give this a shot, it worked for me:
Within the build function of the mail itself (not the view, but the mail):
public function build()
{
return $this
->from($address = 'noreply#example.com', $name = 'Sender name')
->subject('Here is my subject')
->view('emails.welcome');
}
Happy coding :)
If you want global 'from name' and 'from email',
Create these 2 keys in .env file
MAIL_FROM_NAME="global from name"
MAIL_FROM_ADDRESS=support#example.com
And remove 'from' on the controller. or PHP code if you declare manually.
now it access from name and from email.
config\mail.php
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'info#example.com'),
'name' => env('MAIL_FROM_NAME', 'write name if not found in env'),
],
ON my controller.
$conUsBody = '';
$conUsBody .= '<h2 class="text-center">Hello Admin,</h2>
<b><p> '.trim($request->name).' Want some assesment</p></b>
<p>Here are the details:</p>
<p>Name: '.trim($request->name).'</p>
<p>Email: '.trim($request->email).'</p>
<p>Subject: '.trim($request->subject).'</p>';
$contactContent = array('contactusbody' => $conUsBody);
Mail::send(['html' => 'emails.mail'], $contactContent,
function($message) use ($mailData)
{
$message->to('my.personal.email#example.com', 'Admin')->subject($mailData['subject']);
$message->attach($mailData['attachfilepath']);
});
return back()->with('success', 'Thanks for contacting us!');
}
My blade template.
<body>
{!! $contactusbody !!}
</body>
I think that you have an error in your fragment of code. You have
from(config('app.senders.info'), 'My Full Name')
so config('app.senders.info') returns array.
Method from should have two arguments: first is string contains address and second is string with name of sender. So you should change this to
from(config('app.senders.info.address'), config('app.senders.info.name'))
Right now i'm working with Crinsane Laravel Shopping cart. I'm using 5.0
My problem is: I cant turn the variable into values, instead system display it as it is (variable) .
I want to know how exactly query database with specific column base on id , and turn then into values not variable it self .
My code :
public function addcart (){
$products = Product::find(Input::get('id'));
$qty = Input::get('qty');
Cart::add('$products->id', 'products->name', $qty, $products->price, array('size' => 'large'));
$cart_content = Cart::content();
return view('pages.cart')->with('cart_content', $cart_content);
}
When run , it turn to display like this :
Don't wrap $products->id and $products->name in quotes:
Cart::add(
$products->id,
$products->name,
$qty,
$products->price,
['size' => 'large']
);
Is there a built-in way to do something like this?
Let's say I have a search-page that has a few parameters in the URL:
example.com/search?term=foo&type=user
A link on that page would redirect to an URL where type is link. I'm looking for a method to do this without manually constructing the URL.
Edit:
I could build the URL manually like so:
$qs = http_build_query(array(
'term' => Input::get('term'),
'type' => Input::get('type')
));
$url = URL::to('search?'.$qs);
However, what I wanted to know is if there is a nicer, built-in way of doing this in Laravel, because the code gets messier when I want to change one of those values.
Giving the URL generator a second argument ($parameters) adds them to the URL as segments, not in the query string.
You can use the URL Generator to accomplish this. Assuming that search is a named route:
$queryToAdd = array('type' => 'user');
$currentQuery = Input::query();
// Merge our new query parameters into the current query string
$query = array_merge($queryToAdd, $currentQuery);
// Redirect to our route with the new query string
return Redirect::route('search', $query);
Laravel will take the positional parameters out of the passed array (which doesn't seem to apply to this scenario), and append the rest as a query string to the generated URL.
See: URLGenerator::route(),
URLGenerator::replaceRouteParameters()
URLGenerator::getRouteQueryString()
I prefer native PHP array merging to override some parameters:
['type' => 'link'] + \Request::all()
To add or override the type parameter and remove another the term:
['type' => 'link'] + \Request::except('term')
Usage when generating routes:
route('movie::category.show', ['type' => 'link'] + \Request::all())
You can do it with Laravel's URLGenerator
URL::route('search', array(
'term' => Input::get('term'),
'link' => Input::get('type')
));
Edit: be sure to name the route in your routes.php file:
Route::get('search', array('as' => 'search'));
That will work even if you're using a Route::controller()
From Laravel documentation:
if your route has parameters, you may pass them as the second argument
to the route method.
In this case, for return an URI like example.com/search?term=foo&type=user, you can use redirect function like this:
return redirect()->route('search', ['term' => 'foo', 'type' => 'user']);
Yes, there is a built in way. You can do your manipulation in Middleware.
The $request passed to the handle method of all middleware has a query property. As an InputBag, it comes with a few methods; Namely, for your intentions: ->set().
Pretty self explanatory, but here's an example:
public function handle(Request $request, Closure $next)
{
$request->query->set('term','new-value');
// now you pass the request (with the manipulated query) down the pipeline.
return $next($request);
}
The Input component should also contain query parameters.
i.e Input::get('foo');
I would like to add custom variable on new order email notification having value populated from table sales_flat_order (i.e. heared4us ). How can I do this ?
I am using magento version 1.7.0.2
Thanks.
To add new fields to order e-mail you need to follow the following 2 steps
1) Edit sendNewOrderEmail() function located in
app/code/core/Mage/Sales/Model/Order.php
In that function you will find following code
$mailer->setTemplateParams(array(
'order' => $this,
'billing' => $this->getBillingAddress(),
'payment_html' => $paymentBlockHtml,
));
You need to add new key value pair to add new custom value
$mailer->setTemplateParams(array(
'order' => $this,
'billing' => $this->getBillingAddress(),
'payment_html' => $paymentBlockHtml,
'customvalue' => 'This is a custom value' //New custom value
));
2) Now the second part. You need to add the custom variable to new order email template.
Just edit the template add your custom parameter name. in the example it is "customvalue".
{{ var customvalue }}
For English the order e-mail template is located in
app\locale\en_US\template\email\sales\order_new.html
app\locale\en_US\template\email\sales\order_new_guest.html
So depending on your language used in the website select the proper template located inside locale folder.
Also you can edit the e-mail template from admin by navigating to
System > Transactional Emails > New Order Email
public function execute(\Magento\Framework\Event\Observer $observer) {
$transport = $observer->getEvent()->getTransport();
$transportObj = $observer->getData('transportObject');
/** #var \Magento\Framework\App\Action\Action $controller*/
$transport = $observer->getTransport();
$transportObj->setData('custom_content',"custom content 123");
return $transportObj;
}
I'm struggling with a very stupid problem.
I've edited the saveOrder() method in app/code/core/Mage/Checkout/Type/Onepage.php.
This because I wanted to prevent Magento from sending order confirmation email for some payment methods.
Instead of standard emails I'm sending a new one (coded in transactional emails in backend) with different information.
All it's ok, I've done something like:
if($order->getPayment()->getMethodInstance()->getCode()!='X') {
$order->sendNewOrderEmail();
} else {
$name = $order->getBillingAddress()->getName();
$mailer = Mage::getModel('core/email_template_mailer');
$emailInfo = Mage::getModel('core/email_info');
$emailInfo->addTo($order->getCustomerEmail(), $name);
$mailer->addEmailInfo($emailInfo);
$templateId = 3;
$storeId = Mage::app()->getStore()->getId();
$sender = Array('name' => 'XXX', 'email' => 'xxx#xxx.xxx');
$mailer->setSender($sender);
$mailer->setStoreId($storeId);
$mailer->setTemplateId($templateId);
$mailer->setTemplateParams(array(
'order' => $order
)
);
$mailer->send();
}
All works fine except for the total of the order. In the transactional email I'm printing
{{var order.getGrandTotal()}}
but I'm getting the value "0.999953719008" for a 1 euro price product and I don't know how to solve this. (The test product has got a discount)
I've tried creating a script which loads a previously registered order and sends the email using the same email template. In this case all works like a charm!
So I suppose that the problem is because the order isn't saved yet.
I've just tried passing the grand total as another variable using
$mailer->setTemplateParams(array(
'order' => $order,
'total' => $order->getGrandTotal()
)
);
and printing
{{var total}}
in the template and in this case there isn't any value for the variable.
How can I manage to solve this?
Thank in advance!
p.s.: I'm using an installation of 1.6 version of Magento.
I've had this before as well. It's due to php float rounding issues:
http://php.net/manual/en/language.types.float.php
Use round() to display your results correctly to the user. With bcadd() you can avoid the rounding issues if you change the price somewhere with custom code.