Magento Invoice sendEmail() with PDF attachment - magento

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.

Related

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);
}
}

Creating a grid in admin panel on click of a dropdown option magento 1.7.0.2

I'm developing a sub-module in the admin panel. The first page grid shows the list of the users(Referrers / Parent users) and their total commission. In the "Actions" tab there's a drop-down, on click of which some grids get opened. Similar to it, I want to add another option on click of which there should be a page showing who referred (child users) under that Referrer / Parent user and how much commission the Referrer / Parent user got per referral / child user.
For ex: A (Parent user) - B ,C (child users) got registered by the reference of A.
So, From B, A got 20$ commission and from C, A got 20$ commission, (these details of who referred by whom and how much of commission is there is stored in a table) showing total of 40$ on previous page.
The error which I'm getting is-
Fatal error: Uncaught Error: Call to a member function setSaveParametersInSession() on boolean in E:\xampp\htdocs\peoplesoilnew\app\code\core\Mage\Adminhtml\Block\Widget\Grid\Container.php:66 Stack trace: #0 E:\xampp\htdocs\peoplesoilnew\app\code\core\Mage\Core\Block\Abstract.php(238): Mage_Adminhtml_Block_Widget_Grid_Container->_prepareLayout() #1 E:\xampp\htdocs\peoplesoilnew\app\code\core\Mage\Core\Model\Layout.php(456): Mage_Core_Block_Abstract->setLayout(Object(Mage_Core_Model_Layout)) #2 E:\xampp\htdocs\peoplesoilnew\app\code\local\Mj\Friends\controllers\Adminhtml\FriendsController.php(60): Mage_Core_Model_Layout->createBlock('friends/adminht...') #3 E:\xampp\htdocs\peoplesoilnew\app\code\core\Mage\Core\Controller\Varien\Action.php(419): Mj_Friends_Adminhtml_FriendsController->friendscommissionAction() #4 E:\xampp\htdocs\peoplesoilnew\app\code\core\Mage\Core\Controller\Varien\Router\Standard.php(250): Mage_Core_Controller_Varien_Action->dispatch('friendscommissi...') #5 E:\xampp\htdocs\peoplesoilnew\app\code\core\Ma in E:\xampp\htdocs\peoplesoilnew\app\code\core\Mage\Adminhtml\Block\Widget\Grid\Container.php on line 66
Code files-
The code from where the option for drop-down is added -
$this->addColumn('action',
array(
'header' => Mage::helper('customer')->__('Action'),
'width' => '100',
'type' => 'action',
'getter' => 'getId',
'actions' => array(
array(
'caption' => Mage::helper('friends')->__('Make Payment'),
'url' => array('base'=> '*/*/payment'),
'field' => 'friendskey_id'
),
array(
'caption' => Mage::helper('friends')->__('View Referred Friend List'),
'url' => array('base'=> '*/*/friendslist'),
'field' => 'friendskey_id'
),
array(
'caption' => Mage::helper('friends')->__('Distribution of Commission'),
'url' => array('base'=> '*/*/friendscommission'),
'field' => 'friendskey_id'
)
app\code\local\Mj\Friends\etc\config.xml -
<friends_mysql4>
<class>Mj_Friends_Model_Mysql4</class>
<entities>
<friends>
<table>friends</table>
</friends>
<commission>
<table>friends_commission</table>
</commission>
<memberkey>
<table>friendskey</table>
</memberkey>
<friendscommission>
<table>friends_commission</table>
</friendscommission>
</entities>
</friends_mysql4>
app\code\local\Mj\Friends\Block\Adminhtml\Friendscommission\Grid.php -
<?php
class Mj_Friends_Block_Adminhtml_Friendscommission_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
public function __construct()
{
parent::__construct();
$this->setId('friends_commission');
$this->setDefaultSort('commission_id');
$this->setDefaultDir('ASC');
$this->setSaveParametersInSession(false);
$this->_prepareCollection();
}
protected function _prepareCollection()
{
// get the member id using friendskey_id
/*$friendsId = $this->getRequest()->getParam('friendskey_id');
$friendsModel = Mage::getModel('friends/memberkey')->load($friendsId);
$memberId = $friendsModel->getMemberId();*/
$collection = Mage::getModel('friends/friends_commission')->getCollection();
// $collection->addFieldToFilter('member_id', $memberId);
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _prepareColumns()
{
/*
$this->addColumn('friends_id', array(
'header' => Mage::helper('friends')->__('ID'),
'align' =>'right',
'width' => '50px',
'index' => 'friends_id',
));
*/
$this->addColumn('user_email', array(
'header' => Mage::helper('friends')->__('User Email'),
'align' => 'left',
'width' => '120px',
'default' => '--',
'index' => 'user_email',
));
$this->addColumn('status', array(
'header' => Mage::helper('friends')->__('Status'),
'align' => 'left',
'width' => '80px',
'index' => 'status',
'type' => 'options',
'options' => array(
'Active' => 'Active',
'Inactive' => 'Inactive',
),
));
return parent::_prepareColumns();
}
}
app\code\local\Mj\Friends\Block\Adminhtml\Friendscommission.php -
<?php
class Mj_Friends_Block_Adminhtml_Friendscommission extends Mage_Adminhtml_Block_Widget_Grid_Container
{
public function __construct()
{
$this->_controller = 'adminhtml_friendscommission';
$this->_blockGroup = 'friends';
$this->_headerText = Mage::helper('friends')->__('Friends Commission');
//$this->_addButtonLabel = Mage::helper('friends')->__('Add Item');
parent::__construct();
$this->_removeButton('add');
/*
$this->_addButton('back');
$this->_addButton('back_button_id', array(
'label' => Mage::helper('friends')->__('Some action'),
'onclick' => 'jsfunction(this.id)',
'class' => 'go'
), 0, 100, 'header', 'header');
*/
}
}
**app\code\local\Mj\Friends\Model\Friendscommission.php **
<?php
class Mj_Friends_Model_Friendscommission extends Mage_Core_Model_Abstract
{
public function _construct()
{
parent::_construct();
$this->_init('friends/friends_commission');
}
}
From the controller the action for that module is called, app\code\local\Mj\Friends\controllers\Adminhtml\FriendsController.php -
<?php
class Mj_Friends_Adminhtml_FriendsController extends Mage_Adminhtml_Controller_Action
{
protected function _initAction()
{
$this->loadLayout()
->_setActiveMenu('friends/items')
->_addBreadcrumb(Mage::helper('adminhtml')->__('Items Manager'), Mage::helper('adminhtml')->__('Item Manager'));
return $this;
}
public function indexAction() {
$this->_initAction();
$this->_addContent($this->getLayout()->createBlock('friends/adminhtml_friends'));
$this->renderLayout();
}
public function editAction()
{
$friendsId = $this->getRequest()->getParam('id');
$friendsModel = Mage::getModel('friends/friends')->load($friendsId);
if ($friendsModel->getId() || $friendsId == 0) {
Mage::register('friends_data', $friendsModel);
$this->loadLayout();
$this->_setActiveMenu('friends/items');
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item Manager'), Mage::helper('adminhtml')->__('Item Manager'));
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item News'), Mage::helper('adminhtml')->__('Item News'));
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->_addContent($this->getLayout()->createBlock('friends/adminhtml_friends_edit'))
->_addLeft($this->getLayout()->createBlock('friends/adminhtml_friends_edit_tabs'));
$this->renderLayout();
} else {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('friends')->__('Item does not exist'));
$this->_redirect('*/*/');
}
}
public function newAction()
{
$this->_forward('edit');
}
public function friendslistAction() {
$this->_initAction();
$this->_addContent($this->getLayout()->createBlock('friends/adminhtml_friendslist'));
$this->renderLayout();
}
public function friendscommissionAction() {
$this->_initAction();
$this->_addContent($this->getLayout()->createBlock('friends/adminhtml_friendscommission'));
$this->renderLayout();
}
public function paymentAction()
{
$friendsId = $this->getRequest()->getParam('friendskey_id');
$friendsModel = Mage::getModel('friends/memberkey')->load($friendsId);
if ($friendsModel->getFriendskeyId() || $friendsId > 0) {
Mage::register('friends_data', $friendsModel);
$this->loadLayout();
$this->_setActiveMenu('friends/items');
/* $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item Manager'), Mage::helper('adminhtml')->__('Item Manager'));
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item News'), Mage::helper('adminhtml')->__('Item News'));*/
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->_addContent($this->getLayout()->createBlock('friends/adminhtml_friends_payment'))
->_addLeft($this->getLayout()->createBlock('friends/adminhtml_friends_payment_tabs'));
$this->renderLayout();
} else {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('friends')->__('Item does not exist'));
$this->_redirect('*/*/');
}
}
public function saveAction()
{
if ( $this->getRequest()->getPost() ) {
try {
$postData = $this->getRequest()->getPost();
//print_r($postData); die;
if($postData['amount_hidden'] ) {
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_write');
$updateSql = "UPDATE friends_standard_payamount SET standard_amount = '".$postData['standard_payment_amount']."', standard_commission = '".$postData['standard_commission']."'";
$readConnection->query($updateSql);
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Minimum referred payment amount updated successfully.'));
$this->_redirect('new', array('friendskey_id' => $this->getRequest()->getParam('friendskey_id')));
return;
} else {
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_write');
$updateSql = "UPDATE friends_standard_payamount SET standard_commission = '".$postData['commission_amount']."'";
$readConnection->query($updateSql);
//get the commission amount
$friendsModel = Mage::getModel('friends/friends');
$commission_amount = $postData['commission_amount'];
$friendskey_id = $postData['friendskey_id'];
//get the memeber id.
$friendsModel = Mage::getModel('friends/memberkey')->load($friendskey_id);
$memberId = $friendsModel->getMemberId();
//get the member paypal business email address.
$customerData = Mage::getModel('customer/customer')->load($memberId)->getData();
//$customerData['paypalemail'];
if(!empty($customerData['paypalemail'])) {
//get the paypal config settings.
$standard = Mage::getModel('paypal/standard');
$form = new Varien_Data_Form();
$form->setAction($standard->getConfig()->getPaypalUrl())
->setId('paypal_standard_checkout')
->setName('paypal_standard_checkout')
->setMethod('POST')
->setUseContainer(true);
/* #var $api Mage_Paypal_Model_Api_Standard */
$api = Mage::getModel('paypal/api_standard')->setConfigObject($this->getConfig());
//$orderIncrementId = 0 ;
$api->setOrderId($orderIncrementId)
->setCurrencyCode(Mage::app()->getStore()->getCurrentCurrencyCode())
//->setPaymentAction()
//->setOrder($order)
->setNotifyUrl(Mage::getUrl('paypal/ipn/'))
->setReturnUrl(Mage::getUrl('paypal/standard/success'))
->setCancelUrl(Mage::getUrl('paypal/standard/cancel'));
//get and set owner address.
$address = array();
$api->setAddress($address);
$api->setLocale($api->getLocaleCode());
$result = $api->getStandardCheckoutRequest();
foreach ($result as $field=>$value) {
if($field == "business") {
//set the paypal business email address
$form->addField($field, 'hidden', array('name'=>$field, 'value'=>$customerData['paypalemail']));
} else if($field == "return") {
$form->addField($field, 'hidden', array('name'=>$field, 'value'=>$this->getUrl('*/*/success', array())));
} else if($field == "cancel_return") {
$form->addField($field, 'hidden', array('name'=>$field, 'value'=>$this->getUrl('*/*/cancel', array())));
} else {
$form->addField($field, 'hidden', array('name'=>$field, 'value'=>$value));
}
}
$form->addField('amount', 'hidden', array('name'=>'amount', 'value'=>$commission_amount));
$form->addField('paymentaction', 'hidden', array('name'=>'paymentaction', 'value'=>'sale'));
$form->addField('item_name', 'hidden', array('name'=>'item_name', 'value'=>'Commission Amount'));
//$form->addField('business', 'hidden', array('name'=>'business', 'value'=>$paypalBusinessIdValue));
$idSuffix = Mage::helper('core')->uniqHash();
$submitButton = new Varien_Data_Form_Element_Submit(array(
'value' => $this->__('Click here if you are not redirected within 10 seconds...'),
));
$id = "submit_to_paypal_button_{$idSuffix}";
$submitButton->setId($id);
$form->addElement($submitButton);
$html = '<html><body>';
$html.= $this->__('You will be redirected to the PayPal website in a few seconds.');
$html.= $form->toHtml();
$html.= '<script type="text/javascript">document.getElementById("paypal_standard_checkout").submit();</script>';
$html.= '</body></html>';
echo $html;
exit;
}else {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Member does not have the PayPal Email Address. Thus, unable proceed to make the payment.'));
Mage::getSingleton('adminhtml/session')->setFriendsData($this->getRequest()->getPost());
$this->_redirect('*/*/payment', array('friendskey_id' => $this->getRequest()->getParam('friendskey_id')));
return;
}
}
/*
$friendsModel->setId($this->getRequest()->getParam('id'))
->setTitle($postData['user_email'])
->setContent($postData['content'])
->setStatus($postData['status'])
->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Item was successfully saved'));
Mage::getSingleton('adminhtml/session')->setFriendsData(false);
*/
// $this->_redirect('*/*/');
// return;
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setFriendsData($this->getRequest()->getPost());
$this->_redirect('*/*/payment', array('friendskey_id' => $this->getRequest()->getParam('friendskey_id')));
return;
}
}
$this->_redirect('*/*/');
}
public function successAction() {
$this->loadLayout();
$this->_setActiveMenu('friends/items');
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->renderLayout();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Payment has been done successfully.'));
}
public function cancelAction() {
$this->loadLayout();
$this->_setActiveMenu('friends/items');
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->renderLayout();
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Payment has been cancelled successfully.'));
}
public function formAction(){
$this->loadLayout();
$this->getResponse()->setBody(
$this->getLayout()->createBlock('friends/adminhtml_friends_payment_tab_amount')->toHtml()
);
}
/**
* Config instance getter
* #return Mage_Paypal_Model_Config
*/
public function getConfig()
{
if (null === $this->_config) {
$params = array($this->_code);
if ($store = Mage::app()->getStore()) {
$params[] = is_object($store) ? $store->getId() : $store;
}
$this->_config = Mage::getModel('paypal/config', $params);
}
return $this->_config;
}
public function deleteAction()
{
if( $this->getRequest()->getParam('id') > 0 ) {
try {
$friendsModel = Mage::getModel('friends/friends');
$friendsModel->setId($this->getRequest()->getParam('id'))
->delete();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Item was successfully deleted'));
$this->_redirect('*/*/');
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
}
}
$this->_redirect('*/*/');
}
/**
* Product grid for AJAX request.
* Sort and filter result for example.
*/
public function gridAction()
{
$this->loadLayout();
$this->getResponse()->setBody(
$this->getLayout()->createBlock('friends/adminhtml_friends_grid')->toHtml()
);
}
}
The table to fetch data from -
Seems like you are missing the controller "adminhtml_friendscommission"
$this->_controller = 'adminhtml_friendscommission';
Please create the above controller and it will fix the issue.
Or if you dont want that friendscommission controller and if you need to use friends controller change the
$this->_controller = 'adminhtml_friendscommission';
to
$this->_controller = 'adminhtml_friends';
in
Mj_Friends_Block_Adminhtml_Friendscommission::__construct method

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.

Varien_File_Uploader is not uploading files in custom module in magento

I am trying to save the images in my module but the images are not saving from the form.
$uploader = new Varien_File_Uploader('image'); this code is not working I dont know why. The loop breaks on this line and the control get out of the loop from here. How can I save the images.
Here is my save function in the controller
public function saveAction()
{
if ($this->getRequest()->getPost())
{
try
{
$postData = $this->getRequest()->getPost();
//echo "<pre>";print_r($postData); exit;
$articleModel = Mage::getModel('blog/article');
$imgFilename = NULL;
if($_FILES['image']['name'] != '')
{//echo "<pre>"; echo count($_FILES['image']['name']);
foreach($_FILES['image']['name'] as $_FILES['image']['name'])
{
//print_r($_FILES['image']['name']);
try
{ echo "1";
$uploader = new Varien_File_Uploader('image'); echo "hi";
//print_r($uploader);exit;
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png','flv'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$uploader->setAllowCreateFolders(true);
// Set media as the upload dir
$media_path = Mage::getBaseDir('media') . DS . 'blog' . DS;
$imgFilename = time() . $postData['image'];
// Upload the image
//$uploader->save($media_path, $_FILES['image']['name']);echo "4";
$uploader->save($media_path, $imgFilename);
}
catch (Exception $e)
{
Mage::log($e);
$this->_redirectError(502);
}
$data['image'] = $imgFilename;
}
}
else
{
if(isset($data['image']['delete']) && $data['image']['delete'] == 1)
$data['image'] = '';
else
unset($data['image']);
}
//echo "out"; exit;
if( $this->getRequest()->getParam('id') <= 0 )
$articleModel->setCreatedTime(
Mage::getSingleton('core/date')
->gmtDate());
$articleModel
->addData($postData)
->setUpdatedTime(
Mage::getSingleton('core/date')
->gmtDate())
->setId($this->getRequest()->getParam('id'))
->save();
$lastid = $articleModel->getId();
if($data['image'] != '')
{
foreach($data['image'] as $img)
{
$imageModel=Mage::getModel('blog/image');
$imageModel->setArticleId($lastid)->setImage($data['image'])->save();
}
}
Mage::getSingleton('adminhtml/session')
->addSuccess('successfully saved');
Mage::getSingleton('adminhtml/session')
->setarticleData(false);
$this->_redirect('*/*/');
//return;
if ($this->getRequest()->getParam('back'))
{
$this->_redirect('*/*/edit',array('id' => $articleModel->getId()));
return;
}
}
catch (Exception $e)
{
Mage::getSingleton('adminhtml/session')
->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')
->setarticleData($this->getRequest()
->getPost());
$this->_redirect('*/*/edit',
array('id' => $this->getRequest()
->getParam('id')));
return;
}
}
$this->_redirect('*/*/');
}
and here is my form for the image
<?php
class Vertax_Blog_Block_Adminhtml_Article_Edit_Tab_Image extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('image_form',
array('legend'=>'image'));
//$fieldset->addType('image', Mage::getConfig()->getBlockClassName('blog/adminhtml_article_helper_image'));
$fieldset->addType('image', 'Vertax_Blog_Block_Adminhtml_Article_Helper_Image');
$fieldset->addField('image', 'image', array(
'label' => 'Image',
'required' => false,
'name' => 'image[]',
'multiple' => 'multiple',
'mulitple' => true,
));
if (Mage::getSingleton('adminhtml/session')->getBlogPostData()) {
$form->setValues(Mage::getSingleton('adminhtml/session')->getBlogPostData());
Mage::getSingleton('adminhtml/session')->setBlogPostData(null);
} elseif (Mage::registry('article_data')) {
$form->setValues(Mage::registry('article_data')->getData());
}
return parent::_prepareForm();
}
}
?>
$uploader = new Mage_Core_Model_File_Uploader(
array(
'name' => $_FILES['galleryImage']['name'][$i],
'type' => $_FILES['galleryImage']['type'][$i],
'tmp_name' => $_FILES['galleryImage']['tmp_name'][$i],
'error' => $_FILES['galleryImage']['error'][$i],
'size' => $_FILES['galleryImage']['size'][$i]
));
Waseem,please try code for upload image..
$uploader = new Mage_Core_Model_File_Uploader('image');
$uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png'));
$uploader->setFilesDispersion(true);
$media_path = Mage::getBaseDir('media') . DS . 'blog' . DS;
$imgFilename = time() . $postData['image'];
// Upload the image
//$uploader->save($media_path, $_FILES['image']['name']);echo "4";
$uploader->save($media_path, $imgFilename);
there was a problem in your code while adding fieldset
$fieldset->addField('image', 'image', array(
'label' => 'Image',
'required' => false,
'name' => 'image[]',
'multiple' => 'multiple',
'mulitple' => true,
));
here you had set the name to image[] which in turn will return the array as $_FILES['image][name][], $_FILES['image][tmp_name][].
If you want to upload single file then set 'name' = 'image' or see this question
Try to use
$uploader = new Varien_File_Uploader($_FILES['image']);
instead of what you use currently.

render PDF and attach to email (using DOMPDFModule and EmailZF2)

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);
}
}

Resources