Login Function use in custom module controller in magento - 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
}

Related

Laravel 4 - Eloquent relationship find by username

$picture = User::find(Session::get('user_id'))
->pictures()->where('approved', '=', '1')->first();
How can i modify this code according to username instead of Session::get('user_id')
Thanks.
if the user is logged in, try
$pictures = Auth::user()->pictures()->where('approved', '1')->first();
Update
regarding your comment:
try {
$pictures = User::where('name', $searchname)->firstOrFail()->pictures()->where('approved', '1')->first();
}
catch (Exception $e) {
// stuff to do, if no user is found
}

How can I delete a record from database in a ajax request in magento

I have created custom module and I am working on record deletion but its not working. Code which I am using is
$keyId=$params = $this->getRequest()->getParams('id');
$model = Mage::getModel('groupprice/groupprice');
try {
$model->setId($keyId)->delete();
echo "Data deleted successfully.";
} catch (Exception $e){
echo $e->getMessage();
}
Is anything wrong ?
This code is working in a simple request but not working with ajax request .
You should change code and use getPost
$keyId=$params = $this->getRequest()->getPost('id');
Hope this wil help.
Try this code :
$keyId=$params = $this->getRequest()->getParam('id');
$model = Mage::getModel('groupprice/groupprice');
try
{
$model->setId($keyId)->delete();
echo "Data deleted successfully.";
}
catch (Exception $e)
{
echo $e->getMessage();
}

Creating orders programmatically

I try to create an order in code, but sometimes the code works, but sometimes it goes wrong with exception "The requested Payment Method is not available." (first browser request is ok, but the second one goes wrong, etc..).
My code is:
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
$customer = Mage::getSingleton('customer/session')->getCustomer();
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
} else {
$customer = Mage::getModel('customer/customer');
$email = 'test#example.com';
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->setStoreId(Mage::app()->getStore()->getId());
$customer->loadByEmail($email);
Mage::getSingleton('customer/session')->loginById($customer->getId());
}
$customAddress = Mage::getModel('customer/address')
->setCustomerId($customer->getId())
->getCustomer();
$customAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultBilling();
if ($customAddressId) {
$customAddress = Mage::getModel('customer/address')->load($customAddressId);
}
Mage::getSingleton('checkout/session')->getQuote()
->setBillingAddress(Mage::getSingleton('sales/quote_address')->importCustomerAddress($customAddress))
->setShippingAddress(Mage::getSingleton('sales/quote_address')->importCustomerAddress($customAddress));
$product = Mage::getModel('catalog/product')
->setStoreId(Mage::app()->getStore()->getId())
->load(2);
$cart = Mage::getSingleton('checkout/cart');
$cart->truncate();
try {
$cart->addProduct($product, array('qty' => 2));
$cart->save();
$message = $this->__('%s was successfully added to your shopping cart.', $product->getName());
Mage::getSingleton('checkout/session')->addSuccess($message);
} catch (Exception $ex) {
echo $ex->getMessage();
}
$storeId = Mage::app()->getStore()->getId();
$checkout = Mage::getSingleton('checkout/type_onepage');
$checkout->initCheckout();
$checkout->saveCheckoutMethod('register');
$checkout->saveShippingMethod('flatrate_flatrate');
$checkout->savePayment(array('method' => 'banktransfer'));
try {
$checkout->saveOrder();
} catch (Exception $ex) {
echo $ex->getMessage();
}
$cart->truncate();
$cart->save();
$cart->getItems()->clear()->save();
Mage::getSingleton('customer/session')->logout();
I checked your code in my local server, It s working fine 1st time, but second time it shows error like The requested Shipping Method is not available not like you mentioned above. But after I enabled that shipping method it working fine, So try to enable the shipping and payment methods that you used in your code in admin..

Prevent subscriber saving in observer newsletter_subscriber_save_before 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!

How to send email after successful checkout process?

In my store, I have created a custom module for one-step checkout process.
All the code works fine. But the order detail email is not sent to the customer after the checkout process. Here is the relevant part of my code.
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();
$order = $service->getOrder();
//This one is the email send code
$order_mail = new Mage_Sales_Model_Order();
$incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order_mail->loadByIncrementId($incrementId);
$order_mail->sendNewOrderEmail();
$this->_redirect('downloadable/customer/products/');
To send/resend an order email in magento
try {
$incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$_order = Mage::getModel('sales/order')->loadByIncrementId($incrementId);
$_order->sendNewOrderEmail();
$this->_getSession()->addSuccess($this->__('The order email has been sent.'));
} catch (Exception $e) {
$this->_getSession()->addError($this->__('Failed to send the order email.'));
Mage::logException($e);
}
try putting it in a try catch to see what the error is like this
<?php
$order_mail = new Mage_Sales_Model_Order();
$incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order_mail->loadByIncrementId($incrementId);
try
{
$order_mail->sendNewOrderEmail();
} catch (Exception $ex) { }
?>
Did you debug when it goes into sendNewOrderEmail? Maybe this helps to figure out where the problem is?
Regards
Try this,
< ?php
$order = new Mage_Sales_Model_Order();
$incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order->loadByIncrementId($incrementId);
try
{
$order->sendNewOrderEmail();
} catch (Exception $ex) { }
?>
Save the above snippet as .phtml and upload it in app/code/core/Mage.
Now make an order in your site and check after successful checkout Email is sending or not.Hope your problem should solved now.

Resources