Prevent subscriber saving in observer newsletter_subscriber_save_before Magento - magento

I created an Observer to monitor the event subscriber_save_before. In this observer I handle a new field, the value of that is saved, but if some errors occurs I wanna the record not to be saved and to display only my error message. The throwException seems not to do the trick. The only method I think could work is to force the email field to null but wasn't able to achieve this.
In the subscriberController.php (Mage Core) I have this:
$email = (string) $this->getRequest()->getPost('email');
try {
if (!Zend_Validate::is($email, 'EmailAddress')) {
Mage::throwException($this->__('Please enter a valid email address.'));
}
This is my code (not working):
public function NewsletterSaveSubscriber($observer)
{
$subscriber = $observer->getEvent()->getSubscriber();
$name = Mage::app()->getRequest()->getParam('subscriber_name');
// server side validation
// no name specified
if (!Zend_Validate::is(trim($name), 'NotEmpty')) {
$session = Mage::getSingleton('core/session');
try {
Mage::throwException(Mage::helper('newsletter')->__('The name field cannot be empty!'));
} catch (Mage_Core_Exception $e) {
$session->addException($e, Mage::helper('newsletter')->__('There was a problem: %s', $e->getMessage()));
}
$observer->getRequest()->setPost('email', ''); // this code doesn't work
Mage::app()->getRequest()->setPost('email', ''); // this too
// Ohh nooo! The subscriber is stored :-(
return $this;
}
// save the name
$name = htmlspecialchars($name);
$subscriber->setSubscriberName($name);
return $this;
}

This will solve your probem:
//Error Message
$session = Mage::getSingleton('core/session');
$session->getMessages(true);
$session->addError(Mage::helper('cartware_automaticreview')->__('CouldĀ“t save.'));
// Ohh nooo! The subscriber is not stored :)
$controller = $observer->getControllerAction()->setFlag('',Mage_Core_Controller_Varien_Action::FLAG_NO_DISPATCH,true);
$controller->getResponse()->setRedirect(Mage::app()->getRequest()->getServer('HTTP_REFERER'));
return;
Good luck!

Related

Magento Order History Comments: Modify Date

I am creating a script to add orders programmatically in Magento. I need help to change the date of the entries in the Comments History (quote, invoice, shipping, etc.). I can manipulate the date of the order itself (setCreatedAt) and some of the comments related to the creation of the order are correct (e.g. "Sep 29, 2008 8:59:25 AM|Pending Customer Notification Not Applicable"), but I cannot change the date of the comment when I use addStatusHistoryComment...
Here's a snippet of my code:
try {
if(!$order->canInvoice()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
}
$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_OFFLINE);
$invoice->setCreatedAt('2008-09-23 13:05:20');
$invoice->register();
$invoice->getOrder()->setCustomerNoteNotify(true);
$invoice->getOrder()->setIsInProcess(true);
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
- >addObject($invoice->getOrder());
$transactionSave->save();
//END Handle Invoice
//START Handle Shipment
$shipment = $order->prepareShipment();
$shipment->setCreatedAt('2008-09-23 14:20:10');
$shipment->register();
$order->setIsInProcess(true);
$order->addStatusHistoryComment('Shipping message goes here...', true);
$shipment->setEmailSent(true);
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($shipment)
->addObject($shipment->getOrder())
->save();
$track = Mage::getModel('sales/order_shipment_track')
->setShipment($shipment)
->setData('title', 'Some tracking no.')
->setData('number', '111222333444')
->setData('carrier_code', 'fedex') //custom, fedex, ups, usps, dhl
->setData('order_id', $shipment->getData('order_id'))
->save();
//END Handle Shipment
}
catch (Mage_Core_Exception $ex) {
echo "Problem creating order invoice and/or shipment: ".$ex."\n";
}
Thanks in advance.
If I understand your question correctly, you just need to do this:
$comments = $order->getStatusHistoryCollection(true);
$comments now contains a collection of all the status history comments, and you can loop over them with whatever sort of criteria you like.
foreach ($comments as $c) {
if ( /* some stuff */ ) {
$c->setData('created_at',$new_date)->save();
}
}
So this is untested, but should work:
You need to create a new method based off addStatusHistoryComment:
/app/code/core/Mage/Sales/Model/Order.php
/*
* Add a comment to order
* Different or default status may be specified
*
* #param string $comment
* #param string $status
* #return Mage_Sales_Model_Order_Status_History
*/
public function addStatusHistoryComment($comment, $status = false)
{
if (false === $status) {
$status = $this->getStatus();
} elseif (true === $status) {
$status = $this->getConfig()->getStateDefaultStatus($this->getState());
} else {
$this->setStatus($status);
}
$history = Mage::getModel('sales/order_status_history')
->setStatus($status)
->setComment($comment)
->setEntityName($this->_historyEntityName);
->setCreatedAt('2008-09-23 14:20:10'); //I added this line
$this->addStatusHistory($history);
return $history;
}
Obviously you either need to rewrite this method, or refactor the code to do the same.

Login Function use in custom module controller in magento

I am facing problem, I don't know how to use login functionality in my custom module controller without pasting whole code of login. I want to hit the login function through my controller and login function return the session/result.
Please any 1 can me out.
I have 1.4.2 version of magento.
What have you tried ? Have you took a look at the standard magento controller (Mage_Customer_AccountController::loginPostAction) ? it's not so much line of codes ..
$session = Mage::getSingleton('customer/session');
$session->login($username, $password);
and try...catch + message/error handling
Please look app/code/core/Mage/Customer/controllers/AccountController.php and public function loginPostAction(), you will get clear idea how magento handles exception
$session = Mage::getSingleton('customer/session');
try {
$session->login($username, $password);
if ($session->getCustomer()->getIsJustConfirmed()) {
$this->_welcomeCustomer($session->getCustomer(), true);
}
} catch (Mage_Core_Exception $e) {
switch ($e->getCode()) {
case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
$value = Mage::helper('customer')->getEmailConfirmationUrl($login['username']);
$message = Mage::helper('customer')->__('This account is not confirmed. Click here to resend confirmation email.', $value);
break;
case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
$message = $e->getMessage();
break;
default:
$message = $e->getMessage();
}
$session->addError($message);
$session->setUsername($login['username']);
} catch (Exception $e) {
// Mage::logException($e); // PA DSS violation: this exception log can disclose customer password
}

Magento - can't save changed customer GroupId with observer for newsletter_subscriber_save_before event

I built an observer for the newsletter_subscriber_save_before event; this gets fired when a customer subscribes/unsubscribes for newsletters.
I need to change this customers groupID accordingly. It seems i can change the GroupId, but i can't manage to save it. If i call in my code the $customer->save() - method, i run into an infinite loop; same occurs if i try to hook into the newsletter_subscriber_save_after event.
Anyone can help me? Would be much appreciated!
Here's my code in Observer.php :
public function newsletter_subscriber_change($observer) {
try {
// get status of subscriber
$subscriber = $observer->getEvent()->getSubscriber();
$status = $subscriber->getStatus();
$email = $subscriber->getEmail();
$customer = Mage::getSingleton('customer/customer');
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
// here i change the groupId
$customer->setData( 'group_id', 9 );
// if i check the group here, the change applied ...
$customer_group = $customer->getGroupId();
// i tried saving with following, but run into loop
$customer->save();
} catch (Exception $e) {
Mage::log("newsletter_subscriber_change observer failed: " . $e->getMessage());
}
}
You got infinite loop because Mage_Newsletter also capture customer_save_after event to save subscribe data.
You can update group id by raw query like bellow:
public function newsletter_subscriber_change($observer) {
try {
// get status of subscriber
$subscriber = $observer->getEvent()->getSubscriber();
$status = $subscriber->getStatus();
$email = $subscriber->getEmail();
$customer = Mage::getSingleton('customer/customer');
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
$adapter = Mage::getSingleton('core/resource');
/* #var $conn Varien_Db_Adapter_Interface */
$conn = $adapter->getConnection('core_write');
$update = 'UPDATE ' . $customer->getResource()->getTable('customer/customer_enity')
. ' SET group_id = ? WHERE entity_id = ?';
$conn->query($update, array(9, $customer->getId()));
} catch (Exception $e) {
Mage::log("newsletter_subscriber_change observer failed: " . $e->getMessage());
}
}

Redirect , POST and Flashdata issue in Codeigniter

i am developing an application where i need some suggestions. Here is the detail of the problem.
public function form()
{
$this->load->helper('inflector');
$id = $this->uri->segment(3,0);
if($data = $this->input->post()){
$result = $this->form_validation->run();
if($result){
if($id > 0){
// here update code
}else{
$this->mymodel->insert($data);
$this->session->set_flashdata('message','The page has been added successfully.');
$this->redirect = "mycontroller/index";
$this->view = FALSE;
}
}else{
//$this->call_post($data);
$this->session->set_flashdata('message','The Red fields are required');
$this->view = FALSE;
$this->redirect = "mycontroller/form/$id";
}
}else{
$row = $this->mymodel->fetch_row($id);
$this->data[]= $row;
}
}
public function _remap($method, $parameters)
{
if (method_exists($this, $method))
{
$return = call_user_func_array(array($this, $method),$parameters);
}else{
show_404();
}
if(strlen($this->view) > 0)
{
$this->template->build('default',array());
}else{
redirect($this->redirect);
}
}
Here you can see how i am trying to reload the page on failed validation.
Now the problem is that i have to display the flash data on the view form which is only available after redirect and i need to display the validation errors to which are not being displayed on redirect due to the loss of post variable. If i dont use redirect then cant display flashdata but only validation errors. I want both of the functionalities togather. I have tried even creating POSt again like this
public function call_post($data)
{
foreach($data as $key => $row){
$_POST[$key] = $row;
}
}
Which i commented out in the formmethod.How can i achieve this.
Here's a thought.
I think you can add the validation error messages into the flash data. Something like this should work:
$this->session->set_flashdata('validation_error_messages',validation_errors());
Notice the call to the validation_errors function. This is a bit unconventional, but I think it should work. Just make sure that the code are executed after the statement $this->form_validation->run(); to make sure the validation error messages are produced by the Form Validation library.
well i have little different approach hope will help you here it is
mycontroller extend CI_Controller{
function _remap($method,$params){
switch($method){
case 'form':
$this->form($params);
break;
default:
$this->index();
break;
}
}
function form(){
$this->load->helper('inflector');
$id = $this->uri->segment(3,0);
$this->form_validation->set_rules('name','Named','required|trim');
$this->form_validation->set_rules('email','email','required|valid_email|trim');
// if validation fails and also for first time form called
if(!$this->form_validation->run()){
$this->template->build('default',array());
}
else{ // validation passed
$this->save($id)
}
}
function save($id = 0){
$data = $this->input->post();
if($id == 0){
$this->mymodel->insert($data);
$this->session->set_flashdata('message','The page has been added successfully.');
$this->redirect = "mycontroller/index";
$this->view = FALSE;
}else{
// update the field
$this->session->set_flashdata('message','The Red fields are required');
}
redirect("mycontroller/index");
}
}
your form/default view should be like this
<?
if(validation_errors())
echo validation_errors();
elseif($this->session->flashdata('message'))
echo $this->session->flashdata('message');
echo form_open(uri_string());// post data to same url
echo form_input('name',set_value('name'));
echo form_input('email',set_value('email'));
echo form_submit('submit');
echo form_close();
try it if you face any problem post here.

sending mail in magento

How to send email in magento writing an action in index controller?
my index controller;
public function postAction()
{
$post = $this->getRequest()->getPost();
if(!$post) exit;
$translate = Mage::getSingleton('core/translate');
$translate->setTranslateInline(false);
try {
$postObject = new Varien_Object();
$postObject->setData($post);
if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
echo '<div class="error-msg">'.Mage::helper('contacts')->__('Please enter a valid email address. For example johndoe#domain.com.').'</div>';
exit;
}
$storeId = Mage::app()->getStore()->getStoreId();
$emailId = Mage::getStoreConfig(self::XML_PATH_SAMPLE_EMAIL_TEMPLATE);
$mailTemplate = Mage::getModel('core/email_template');
$mailTemplate->setDesignConfig(array('area'=>'frontend', 'store'=>$storeId))
->setReplyTo($post['email'])
->sendTransactional($templateId, $sender, $email, $name, $vars=array(), $storeId=null)
if (!$mailTemplate->getSentSuccess()) {
echo '<div class="error-msg">'.Mage::helper('contacts')->__('Unable to submit your request. Please, try again later.').'</div>';
exit;
}
$translate->setTranslateInline(true);
echo '<div class="success-msg">'.Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.').'</div>';
}
catch (Exception $e) {
$translate->setTranslateInline(true);
echo '<div class="error-msg">'.Mage::helper('contacts')->__('Unable to submit your request. Please, try again later.').$e.'</div>';
exit;
}
}
is there any wrong..
please help me to out of this..
Thanks in advance..
Here's another way, if you don't need templates.
Call from a controller.
<?php
$body = "Hi there, here is some plaintext body content";
$mail = Mage::getModel('core/email');
$mail->setToName('John Customer');
$mail->setToEmail('customer#email.com');
$mail->setBody($body);
$mail->setSubject('The Subject');
$mail->setFromEmail('yourstore#url.com');
$mail->setFromName("Your Name");
$mail->setType('text');// You can use 'html' or 'text'
try {
$mail->send();
Mage::getSingleton('core/session')->addSuccess('Your request has been sent');
$this->_redirect('');
}
catch (Exception $e) {
Mage::getSingleton('core/session')->addError('Unable to send.');
$this->_redirect('');
}
It looks like there are a few problems with the way you are calling sendTransactional(). First off, $templateId is not defined, it looks like you've actually stored the template id in $emailId. Also, $sender, $email, and $name are undefined. You can try something like this:
->sendTransactional($emailId, 'general', $post['email'], "Need a send to name here")
This is only going to work if you are getting a valid template id back from your call to getStoreConfig(). You'll also need to set the last name param correctly.
There could be other issues, but that's what I noticed with a quick glance anyway.
Finally i created a function for sending mail by using zend
public function sendMail()
{
$post = $this->getRequest()->getPost();
if ($post){
$random=rand(1234,2343);
$to_email = $this->getRequest()->getParam("email");
$to_name = 'Hello User';
$subject = ' Test Mail- CS';
$Body="Test Mail Code : ";
$sender_email = "sender#sender.com";
$sender_name = "sender name";
$mail = new Zend_Mail(); //class for mail
$mail->setBodyHtml($Body); //for sending message containing html code
$mail->setFrom($sender_email, $sender_name);
$mail->addTo($to_email, $to_name);
//$mail->addCc($cc, $ccname); //can set cc
//$mail->addBCc($bcc, $bccname); //can set bcc
$mail->setSubject($subject);
$msg ='';
try {
if($mail->send())
{
$msg = true;
}
}
catch(Exception $ex) {
$msg = false;
//die("Error sending mail to $to,$error_msg");
}
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($msg));
}
}

Resources