render PDF and attach to email (using DOMPDFModule and EmailZF2) - pdf-generation

In ZF2, I'm trying to generate a PDF using DOMPDFModule and email it using EmailZF2.
Here's what I'm doing in my controller:
// fetch data
$user = $this->getEntityManager()->getRepository('Application\Entity\Users')->find(1);
$address = $this->getEntityManager()->getRepository('Application\Entity\Addresses')->find(1);
// generate PDF
$pdf = new PdfModel();
$pdf->setOption('filename', 'Renter_application-report-' . date("Y_m_d"));
$pdf->setOption('paperSize', 'a4');
$pdf->setVariables(array(
'User' => $user,
'Address' => $address,
));
So far all good, however DOMPDFModule would require me to return $pdf to prompt the PDF generated, and none of the DOMPDF seemed to work (e.g. $pdf->render() or $pdf->output()).
I tried also to render the view myself unsuccessfully as follows (maybe some issue with headers generation?)
// Render PDF
$pdfView = new ViewModel($pdf);
$pdfView->setTerminal(true)
->setTemplate('Application/index/pdf')
->setVariables(array(
'User' => $user,
'Address' => $address,
));
$pdfOutput = $this->getServiceLocator()
->get('viewrenderer')
->render($pdfView);
Lastly, the goal would be to get this rendered PDF and wither save it somewhere to be able to attach it or to attach it straight away - even as simple as
// Save PDF to disk
$file_to_save = '/path/to/pdf/file.pdf';
file_put_contents($file_to_save, $pdfOutput);
// Send Email
$view = new ViewModel(array(
'name' => $User->getName(),
));
$view->setTerminal(true);
$view->setTemplate('Application/view/emails/user');
$this->mailerZF2()->send(array(
'to' => $User->getEmail(),
'subject' => 'Test email'
), $view, $file_to_save);
Which I manage to make working by editing the file \src\EmailZF2\Controller\Plugin\Mailer.php with these lines to attach the PDF:
...
public function send($data = array(), $viewModel, $pdf)
...
if($pdf && file_exists($pdf)) {
$pdf = fopen($pdf, 'r');
$MessageAttachment = new MimePart($pdf);
$MessageAttachment->type = 'application/pdf';
$MessageAttachment->filename = 'output.pdf';
$MessageAttachment->encoding = \Zend\Mime\Mime::ENCODING_BASE64;
$MessageAttachment->disposition = \Zend\Mime\Mime::DISPOSITION_ATTACHMENT;
}
...
$body_html = new MimeMessage();
$body_html->setParts(array($text, $html, $MessageAttachment));
Any help is appreciated, thank you! :)

I don't know if this id the right way, but I managed to make it working so I'll be posting how we did it in case somebody else will encounter the same issue.
I've used DOMPDFModule as base engine, and then in the controller, in the action that generates the PDF, I rendered the PDF through a Viewmodel to use the view scripts as templates
use Zend\View\Model\ViewModel,
DOMPDFModule\View\Model\PdfModel;
...
public function indexAction()
{
$User = $this->getEntityManager()->getRepository('Application\Entity\Users')->find(1);
// generate PDF
$pdf = new PdfModel();
$pdf->setOption('filename', 'user_details-' . date("Y_m_d"));
$pdf->setOption('paperSize', 'a4');
$pdf->setVariables(array(
'User' => $User,
));
// Render PDF
$pdfView = new ViewModel($pdf);
$pdfView->setTerminal(true)
->setTemplate('Application/index/pdf.phtml')
->setVariables(array(
'User' => $User,
));
$html = $this->getServiceLocator()->get('viewpdfrenderer')->getHtmlRenderer()->render($pdfView);
$eng = $this->getServiceLocator()->get('viewpdfrenderer')->getEngine();
$eng->load_html($html);
$eng->render();
$pdfCode = $eng->output();
// Send the email
$mailer->sendEmail($User->getId(), $pdfCode);
}
The emailzf2 module has also been deprecated, and custom mailer module now manages the attachment and sending of emails. To do so, in Mailer/config/module.config.php a new service has been registered:
'view_manager' => array(
'template_path_stack' => array(
__DIR__ . '/../view',
),
),
'service_manager' => array(
'factories' => array(
__NAMESPACE__ . '\Service\MailerService' => __NAMESPACE__ . '\Service\MailerServiceFactory',
),
),
Which references to the file Mailer/src/Mailer/Service/MailerServiceFactory.php:
<?php
namespace Mailer\Service;
use Mailer\Service\MailerService;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class MailerServiceFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$entityManager = $serviceLocator->get('Doctrine\ORM\EntityManager');
$viewRenderer = $serviceLocator->get('ViewRenderer');
$config = $serviceLocator->get('config');
return new MailerService($entityManager, $viewRenderer, $config);
}
}
And Mailer/src/Mailer/Service/MailerService.php:
use Zend\Mime\Message as MimeMessage;
use Zend\View\Model\ViewModel;
class MailerService
{
protected $em;
protected $view;
protected $config;
protected $options;
protected $senderName;
protected $senderEmail;
public function __construct(\Doctrine\ORM\EntityManager $entityManager, $viewRenderer, $config)
{
$this->em = $entityManager;
$this->view = $viewRenderer;
$this->config = $config;
$this->options = array(
'name' => $config['mailer']['smtp_host'],
);
$this->senderName = $config['mailer']['sender']['from_name'];
$this->senderEmail = $config['mailer']['sender']['from_address'];
}
protected function send($fromAddress, $fromName, $toAddress, $toName, $subject, $bodyParts)
{
// setup SMTP options
$options = new Mail\Transport\SmtpOptions($this->options);
$mail = new Mail\Message();
$mail->setBody($bodyParts);
$mail->setFrom($fromAddress, $fromName);
$mail->setTo($toAddress, $toName);
$mail->setSubject($subject);
$transport = new Mail\Transport\Smtp($options);
$transport->send($mail);
}
protected function setBodyHtml($content, $pdf = null, $pdfFilename = null) {
$html = new MimePart($content);
$html->type = "text/html";
$body = new MimeMessage();
if ($pdf != '') {
$pdfAttach = new MimePart($pdf);
$pdfAttach->type = 'application/pdf';
$pdfAttach->filename = $pdfFilename;
$pdfAttach->encoding = \Zend\Mime\Mime::ENCODING_BASE64;
$pdfAttach->disposition = \Zend\Mime\Mime::DISPOSITION_ATTACHMENT;
$body->setParts(array($html, $pdfAttach));
} else {
$body->setParts(array($html));
}
return $body;
}
public function sendEmail($UserId)
{
$User = $this->em->getRepository('Application\Entity\Users')->find($UserId);
$vars = array( 'firstname' => $User->getFirstname(),
'lastname' => $User->getLastname());
$content = $this->view->render('emails/user-profile', $vars);
$body = $this->setBodyHtml($content);
$sendToName = $User->getOaFirstname() .' '. $User->getLastname();
$this->send($this->senderEmail, $this->senderName, $User->getEmailAddress(), $sendToName, 'User profile', $body);
}
}

Related

Update text field value in the configuration screen of the module when click a button

I am designing a module to calculate the VAT between two dates. I already have everything working, it already calculates the VAT perfectly, but now I want it to be displayed on the configuration screen of the module when clicking on save settings. It's the only thing I'm missing. Right now if I want the VAT to be shown I have to exit and re-enter the module configuration screen. Right now where I try to update the VAT field is in the postProcess() function, with this line:Configuration::updateValue($this->name . '_iva', $ivaAcumulado);
<?php
if (!defined('_PS_VERSION_')) {
exit;
}
class moduloResumenIva extends Module {
protected $config_form = false;
public function __construct() {
$this->name = 'moduloResumenIva';
$this->tab = 'administration';
$this->version = '1.0.0';
$this->author = 'luilli';
$this->need_instance = 0;
/**
* Set $this->bootstrap to true if your module is compliant with bootstrap (PrestaShop 1.6)
*/
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('moduloResumenIva');
$this->description = $this->l('mi nuevo modulo mi nuevo modulomi nuevo modulomi nuevo modulomi nuevo modulo');
$this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
}
/**
* Don't forget to create update methods if needed:
* http://doc.prestashop.com/display/PS16/Enabling+the+Auto-Update
*/
public function install() {
Configuration::updateValue('MIMODULOMISMADB_LIVE_MODE', false);
return parent::install() &&
$this->registerHook('header') &&
$this->registerHook('actionPaymentConfirmation') &&
$this->registerHook('backOfficeHeader');
}
public function uninstall() {
Configuration::deleteByName('MIMODULOMISMADB_LIVE_MODE');
return parent::uninstall();
}
/**
* Load the configuration form
*/
public function getContent() {
/**
* If values have been submitted in the form, process.
*/
if (((bool) Tools::isSubmit('submitButton')) == true) {
$this->postProcess();
}
$this->context->smarty->assign('module_dir', $this->_path);
$output = $this->context->smarty->fetch($this->local_path . 'views/templates/admin/configure.tpl');
return $output . $this->renderForm();
}
/**
* Create the form that will be displayed in the configuration of your module.
*/
protected function renderForm() {
$values = array();
$this->fields_form = array();
$this->context->controller->addJqueryUI('ui.datepicker');
$defaultDate = date('Y-m-d');
if (!Configuration::get($this->name . 'my_date_desde')) {
$values['my_date_desde'] = Tools::getValue('my_date_desde', $defaultDate);
} else {
$values['my_date_desde'] = Tools::getValue('my_date_desde', Configuration::get($this->name . '_my_date_desde'));
}
if (!Configuration::get($this->name . 'my_date_hasta')) {
$values['my_date_hasta'] = Tools::getValue('my_date_hasta', $defaultDate);
} else {
$values['my_date_hasta'] = Tools::getValue('my_date_hasta', Configuration::get($this->name . '_my_date_hasta'));
}
$values['iva'] = Tools::getValue('iva', Configuration::get($this->name . '_iva'));
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$lang = new Language((int) Configuration::get('PS_LANG_DEFAULT'));
$helper->default_form_language = $lang->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$helper->identifier = $this->identifier;
$helper->submit_action = 'Submit' . $this->name;
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false) . '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => $values,
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
);
return $helper->generateForm(array($this->getConfigForm()));
}
/**
* Create the structure of your form.
*/
protected function getConfigForm() {
return array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs'
),
'input' => array(
array(
'type' => 'date',
'label' => $this->l('Desde'),
'name' => 'my_date_desde',
'required' => true,
),
array(
'type' => 'date',
'label' => $this->l('Hasta'),
'name' => 'my_date_hasta',
'required' => true,
),
array(
'type' => 'text',
'label' => $this->l('Iva'),
'name' => 'iva',
)
),
'submit' => array(
'title' => $this->l('Save settings'),
'class' => 'button btn btn-default pull-right',
'name' => 'submitButton',
)
),
);
}
/**
* Set values for the inputs.
*/
protected function getConfigFormValues() {
return array(
'CAMPOID' => Configuration::get('CAMPOID', null),
'MIMODULOMISMADB_ACCOUNT_USUARIO' => Configuration::get('MIMODULOMISMADB_ACCOUNT_USUARIO', null),
'MIMODULOMISMADB_ACCOUNT_PASSWORD' => Configuration::get('MIMODULOMISMADB_ACCOUNT_PASSWORD', null),
'my_date_desde' => Configuration::get('my_date_desde', null),
'my_date_hasta' => Configuration::get('my_date_hasta', null),
'iva' => Configuration::get('iva', null),
);
}
/**
* Save form data.
*/
protected function postProcess() {
if (Tools::isSubmit('Submit' . $this->name)) {
if (Tools::getValue('my_date_desde')) {
Configuration::updateValue($this->name . '_my_date_desde', Tools::getValue('my_date_desde'));
}
if (Tools::getValue('my_date_hasta')) {
Configuration::updateValue($this->name . '_my_date_hasta', Tools::getValue('my_date_hasta'));
}
$fechaDesde = Configuration::get($this->name . '_my_date_desde', null) . " 00:00:00";
$fechaHasta = Configuration::get($this->name . '_my_date_hasta', null) . " 00:00:00";
$db = \Db::getInstance();
$sql = "select * from orders where date_add BETWEEN '" . $fechaDesde . "' AND '" . $fechaHasta . "'";
$ivaAcumulado = 0;
$result = $db->executeS($sql);
foreach ($result as $row) {
$ivaAcumulado += $row["total_paid_tax_incl"] - $row["total_paid_tax_excl"];
}
Configuration::updateValue($this->name . '_iva', $ivaAcumulado);
}
}
/**
* Add the CSS & JavaScript files you want to be loaded in the BO.
*/
public function hookBackOfficeHeader() {
if (Tools::getValue('module_name') == $this->name) {
$this->context->controller->addJS($this->_path . 'views/js/back.js');
$this->context->controller->addCSS($this->_path . 'views/css/back.css');
}
}
/**
* Add the CSS & JavaScript files you want to be added on the FO.
*/
public function hookHeader() {
//mail("luilli.guillan#gmail.com", "hola", "viva el vino");
$this->context->controller->addJS($this->_path . '/views/js/front.js');
$this->context->controller->addCSS($this->_path . '/views/css/front.css');
}
}
You can do the redirection after saving the changes:
https://github.com/PrestaShop/contactform/blob/dev/contactform.php#L99
if (((bool) Tools::isSubmit('submitButton')) == true) {
$this->postProcess();
Tools::redirectAdmin($this->context->link->getAdminLink('AdminModules') . '&configure=' . $this->name . '&conf=6');
}
As of now, I see that you don't have any validation, so this solution should be enough.

How to make the field reuired in Yii2 recaptcha google extension himiklab

I am using extension himiklab for yii2 recaptcha, which is similar to the google one. I want to set this field as required field in my rules. When I set it as below it is not validating even If I don't click the checkbox.
[['reCaptcha'], 'required'],
['reCaptcha', \himiklab\yii2\recaptcha\ReCaptchaValidator::className(), 'secret' => '***','skipOnEmpty' => false],
view
<?= $form->field($model, 'reCaptcha')->widget(
\himiklab\yii2\recaptcha\ReCaptcha::className(),
['siteKey' => '6LeY1BAUAAAAALThRhBQ-sJaXbP0Z5i9XFuaz_VW']
)->label(false); ?>
action
public function actionSignup()
{
$browser = new Browser;
if( $browser->getBrowser() == Browser::BROWSER_IE && $browser->getVersion() < 11 )
{
return $this->render('browser');
}
$company = new Company();
$model = new SimUser(['scenario' => SimUser::SCENARIO_REGISTER]);
if ($model->load(Yii::$app->request->post())&& $model->validate() && $company->load(Yii::$app->request->post())&& $company->validate()) {
$model->scenario = SimUser::SCENARIO_REGISTER;
$model->setPassword($model->user_password_hash);
// $model->setCaptcha($model->captcha);
$model->generateAuthKey();
$token = Yii::$app->security->generateRandomString();
$model->user_access_token = $token;
$model->user_verify = 1;
// $company->save();
$model->company_id = 3;
// $model->save();
$model->user_id = 44;
var_dump($model->validate());exit();
if ($model->validate()){
// $auth = Yii::$app->authManager;
// $authorRole = $auth->getRole('Company Admin');
// $auth->assign($authorRole, $model->user_id);
$path = 'C:/wamp/www/test.qsims.com/web/gentelella-1.2.0/production/images/DCMLogo.png';
Yii::$app->mailer->compose('#app/mail/layouts/verify',['model' => $model, 'path' => $path,'token' => $model->user_access_token])
->setTo($model->user_email)
->setFrom('test.qsims#gmail.com')
->setSubject('Welcome to Qsims'.$model->user_fname." ".$model->user_lname.'. Verify your account to continue')
->setTextBody('Verify Account')
->send();
}
// \Yii::$app->user->login($model);
return $this->redirect(['site/verify-new']);
}
return $this->render('signup', [
'model' => $model,
'company' => $company,
]);
}
Where am I going wrong?
Add this to the model
Public $reCaptcha;
add this to rules
['reCaptcha', 'reCaptchaValidator']
call the custom validation
public function reCaptchaValidator($attribute)
{
$validator = new ReCaptchaValidator;
if (!$validator->validate($this->reCaptcha, $error)) {
$this->addError($attribute, $error);
}
}

getting an error Undefined property: stdClass::$id

I've issue with my CMS whenever I tried to Add new page with the following line of code
<?php echo form_open_multipart('admin/page/edit/'. $page->id); ?>
it gives me error
A PHP Error was encountered
Severity: Notice
Message: Undefined property: stdClass::$id
Filename: page/edit.php
Line Number: 5
my edit function is this which perform add & update functionality
public function edit($id = NULL) {
//Fetch a page or set new one
if ($id) {
$this->data['page'] = $this->page_m->get($id);
count($this->data['page']) || $this->data['errors'][] = 'Page Could not be found';
} else {
$this->data['page'] = $this->page_m->get_new();
}
$id == NULL || $this->data['page'] = $this->page_m->get($id);
//Pages for dropdown
$this->data['pages_no_parents'] = $this->page_m->get_no_parents();
//dump($this->data['pages_no_parents']);
//Setup form
$rules = $this->page_m->rules;
$this->form_validation->set_rules($rules);
//Process the form
if ($this->form_validation->run() == TRUE) {
$data = $this->page_m->array_from_post(array(
'title',
'slug',
'order',
'body',
'template',
'parent_id',
'filename'
));
/* * ***********WORKING FOR IMAGE UPLOAD AND SAVE PATH TO DATABASE*************** */
if (!empty($_FILES['filename'])) {
$fdata = $this->do_upload('filename'); /// you are passing the parameter here
$data['filename'] = base_url() . 'uploads/' . $fdata;
}
$this->page_m->save($data, $id);
// echo '<pre>' . $this->db->last_query() . '</pre>';
redirect('admin/page');
}
//Load the view
$this->data['subview'] = 'admin/page/edit';
$this->load->view('admin/_layout_main', $this->data);
}
public function do_upload($field_name) { // but not retriveing here do this
$field_name = 'filename';
$config = array(
'allowed_types' => '*',
'max_size' => '1024',
'max_width' => '1024',
'max_height' => '768',
'upload_path' => './uploads/'
);
$this->load->library('upload');
$this->upload->initialize($config);
if (!$this->upload->do_upload($field_name)) {
echo $this->upload->display_errors();
die();
$this->data['error'] = array('error' => $this->upload->display_errors());
//$this->data['subview'] = 'admin/page/edit';
//$this->load->view('admin/_layout_main', $this->data);
} else {
$fInfo = $this->upload->data();
//return $fInfo['file_path'].$fInfo['file_name'];
// $this->filename = $fInfo;
return $fInfo['file_name'];
}
}
<?php echo form_open_multipart('admin/page/edit/'. ((isset($page->id)) ? $page->id : '')); ?>
As I mentioned in my comment, if you are creating a new record (I assume:) your page object will not have an id yet, so you just have to do a quick check to make sure it exists and if not output an empty string.

Laravel 4 code organization

I have some questions to Laravel 4 code organization. I am not the best "clean coder" and come from the Java world and sometimes my PHP / Laravel 4 code looks terrible. I post an example here from my controller:
public function postCreate()
{
$input = array(
'title' => Binput::json('title'),
'gender' => Binput::json('gender'),
'first' => Binput::json('first'),
'last' => Binput::json('last'),
'birthdate' => Binput::json('birthdate'),
'birthplace' => Binput::json('birthplace'),
'citizenship' => Binput::json('citizenship'),
'organizationId' => Binput::json('organizationId'),
'typeId' => Binput::json('typeId'),
'email' => Binput::json('email'),
'phone_private' => Binput::json('phone_private'),
'phone_mobile' => Binput::json('phone_mobile'),
'address_street' => Binput::json('address.street'),
'address_postcode' => Binput::json('address.postcode'),
'address_city' => Binput::json('address.city'),
'address_country' => Binput::json('address.country'),
'educations' => Binput::json('educations'),
'selectedLanguages' => Binput::json('selectedLanguages'),
'work' => Binput::json('work'),
);
$rules = array (
'gender' => 'required|max:1',
'first' => 'required|min:2',
'last' => 'required|min:2',
'birthdate' => 'required',
'organizationId' => 'required',
'typeId' => 'required',
'email' => 'required|email',
);
$v = Validator::make($input, $rules);
if ($v->fails() || empty($input['educations']))
{
$data = array("flash" => 'Firstname, Lastname, Birthdate, Email and at least 1 entry in Educations required.');
return Response::json($data, 500);
}
try {
DB::connection()->getPdo()->beginTransaction();
$member = new Member();
$member->title = $input['title'];
$member->gender = $input['gender'];
$member->first = $input['first'];
$member->last = $input['last'];
$member->birthdate = $input['birthdate'];
$member->birthplace = $input['birthplace'];
$member->citizenship = $input['citizenship'];
$work = new Work();
$work->working = $input['work']['working'];
if($input['work']['working'] == 1){
$work->branch = $input['work']['branch'];
$work->company = $input['work']['company'];
}
$work->save();
$member->work()->associate($work);
$member->save();
foreach($input['educations'] as $eduInput){
$edu = new Education();
$edu->degree = $eduInput['degree'];
if(!empty($eduInput['course'])){
$edu->course = $eduInput['course'];
}
$edu->term = $eduInput['term'];
$edu->completion = $eduInput['completion'];
if(!empty($eduInput['faculty'])){
try{
$faculty = Faculty::findOrFail($eduInput['faculty']['id']);
$edu->faculty()->associate($faculty);
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
}
}
if($eduInput['institutionId'] == 0){
// University
try{
$university = University::findOrFail($eduInput['university']['id']);
$edu->university()->associate($university);
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
}
}else{
// Freetext
$edu->institution = $eduInput['institution'];
}
$edu->save();
$member->educations()->save($edu);
}
foreach($input['selectedLanguages'] as $languageInput){
try{
$lang = Language::findOrFail($languageInput['id']);
$member->languages()->attach($lang);
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
}
}
try{
$memberType = MemberType::findOrFail($input['typeId']);
$member->memberType()->associate($memberType);
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
}
try{
$organization = Organization::findOrFail($input['organizationId']);
$member->organizations()->attach($organization);
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
}
$email = new Email();
$email->email = $input['email'];
$email->primary = true;
$member->emails()->save($email);
// If input for phone is empty
$phone = new Phone();
$phone->phone = $input['phone_private'];
$phone->phoneType()->associate(PhoneType::find(PhoneType::PRIVATE_PHONE));
$member->phones()->save($phone);
$phone = new Phone();
$phone->phone = $input['phone_mobile'];
$phone->phoneType()->associate(PhoneType::find(PhoneType::MOBILE_PHONE));
$member->phones()->save($phone);
$address = new Address();
$address->street = $input['address_street'];
$address->postcode = $input['address_postcode'];
$address->city = $input['address_city'];
$address->country = $input['address_country'];
$address->member()->associate($member);
$address->save();
DB::connection()->getPdo()->commit();
}catch (\PDOException $e) {
DB::connection()->getPdo()->rollBack();
return Response::json("Error while writing to database.", 500);
}
$member->load('emails');
$data = array("flash" => 'Member created successfully.');
return Response::json($data, 200);
}
This is an example from my controller.
Is it normal to get all parameters in this way. It takes much of space.
Can I move my database transaction elsewhere and not storing in the controller ?
In general where to store the code that manages logic ? In the controller ? In the
model ?
Your controller actions are just a sort of middleware in the sense that in there you should not put any of your business logic. a few pointers I can provide:
you can get all the json input with Input::json()->all() which returns an array so you can operate it.
Validation rules are another responsibility so it should be abstracted in another class that you call from the controller, it also may be well suited in your models(or entities).
To help you understand how can you use another class inside your controllers you should look for dependency injection in the laravel docs.
if you can get access to this book https://leanpub.com/laravel by Laravel's creator it will help your understanding of code organization and class responsibilities even outside laravel

Magento Invoice sendEmail() with PDF attachment

I use the following code to load an invoice and send email programatically:
<?php
$invoice = Mage::getModel('sales/order_invoice')
->loadByIncrementId($invoice_queue['increment_id']);
if (null !== $invoice->getId()){
$invoice->sendEmail();
echo "- Done Invoice #". $invoice_queue['increment_id'] ."\r\n";
}
$invoice = null;
?>
This appears to be sending the invoice email correctly. However, the PDF attachment of the invoice isn't there in the email.
If I were to send the email via magento, it works.
Any idea how to get the PDF to be attached, when calling sendEmail() function?
For sending invoice email you need to overwrite
In mage/core/model/email/template.php add this method at the end of the file:
public function addAttachment(Zend_Pdf $pdf){
$file = $pdf->render();
$attachment = $this->getMail()->createAttachment($file);
$attachment->type = 'application/pdf';
$attachment->filename = 'test.pdf';
}
2 In sales/model/order/Invoice.php add the code between comments(2 lines of code) to the function sendEmail like this:
<?php
public function sendEmail($notifyCustomer=true, $comment='')
{
if (!Mage::helper('sales')->canSendNewInvoiceEmail($this->getOrder()->getStore()->getId())) {
return $this;
}
$currentDesign = Mage::getDesign()->setAllGetOld(array(
'package' => Mage::getStoreConfig('design/package/name', $this->getStoreId()),
'store' => $this->getStoreId()
));
$translate = Mage::getSingleton('core/translate');
/* #var $translate Mage_Core_Model_Translate */
$translate->setTranslateInline(false);
$order = $this->getOrder();
$copyTo = $this->_getEmails(self::XML_PATH_EMAIL_COPY_TO);
$copyMethod = Mage::getStoreConfig(self::XML_PATH_EMAIL_COPY_METHOD, $this->getStoreId());
if (!$notifyCustomer && !$copyTo) {
return $this;
}
$paymentBlock = Mage::helper('payment')->getInfoBlock($order->getPayment())
->setIsSecureMode(true);
$mailTemplate = Mage::getModel('core/email_template');
if ($order->getCustomerIsGuest()) {
$template = Mage::getStoreConfig(self::XML_PATH_EMAIL_GUEST_TEMPLATE, $order->getStoreId());
$customerName = $order->getBillingAddress()->getName();
} else {
$template = Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE, $order->getStoreId());
$customerName = $order->getCustomerName();
}
// attachment here
$pdf = Mage::getModel('sales/order_pdf_invoice')->getPdf(array($this));
$mailTemplate->addAttachment($pdf);
if ($notifyCustomer) {
$sendTo[] = array(
'name' => $customerName,
'email' => $order->getCustomerEmail()
);
if ($copyTo && $copyMethod == 'bcc') {
foreach ($copyTo as $email) {
$mailTemplate->addBcc($email);
}
}
// enter code here
}
if ($copyTo && ($copyMethod == 'copy' || !$notifyCustomer)) {
foreach ($copyTo as $email) {
$sendTo[] = array(
'name' => null,
'email' => $email
);
}
}
foreach ($sendTo as $recipient) {
$mailTemplate->setDesignConfig(array('area'=>'frontend', 'store'=>$order->getStoreId()))
->sendTransactional(
$template,
Mage::getStoreConfig(self::XML_PATH_EMAIL_IDENTITY, $order->getStoreId()),
$recipient['email'],
$recipient['name'],
array(
'order' => $order,
'invoice' => $this,
'comment' => $comment,
'billing' => $order->getBillingAddress(),
'payment_html'=> $paymentBlock->toHtml(),
)
);
}
$translate->setTranslateInline(true);
Mage::getDesign()->setAllGetOld($currentDesign);
return $this;
} ?>
Now when you create an invoice from the back office and you select to notify customer a pdf attachment should be sent as well.

Resources