I need to perform the next action when a customer is making the purchase of products:
If there is a product with custom options to display only a method of payment and if no other method.
how to do this ... I'm going crazy
thanks
You can do this event observer
create an extension under app/code/local
Bh_ZeroSubtotalpaymentmethod_Model
File of extension are config.xml under
app/code/local/Bh/ZeroSubtotalpaymentmethod/etc
and it code is
<?xml version="1.0" ?>
<config>
<modules>
<Bh_ZeroSubtotalpaymentmethod>
<version>1.0.1</version>
</Bh_ZeroSubtotalpaymentmethod>
</modules>
<global>
<models>
<zerosubtotalpaymentmethod>
<class>Bh_ZeroSubtotalpaymentmethod_Model</class>
</zerosubtotalpaymentmethod>
</models>
</global>
<frontend>
<events>
<payment_method_is_active>
<observers>
<paymentfilter_payment_method_is_active>
<type>singleton</type>
<class>zerosubtotalpaymentmethod/observer</class>
<method>filterpaymentmethod</method>
</paymentfilter_payment_method_is_active>
</observers>
</payment_method_is_active>
</events>
</frontend>
</config>
and Observer file code
is
<?php
class Bh_ZeroSubtotalpaymentmethod_Model_Observer {
public function filterpaymentmethod(Varien_Event_Observer $observer) {
/* call get payment method */
$method = $observer->getEvent()->getMethodInstance();
if($method->getCode()=='paypal_standard')
{ $quote = $observer->getEvent()->getQuote();
if($this->checkcustomoption()==true){
$result = $observer->getEvent()->getResult();
$result->isAvailable = false;
}
return;
}
if($method->getCode()=='free'){
$quote = $observer->getEvent()->getQuote();
if($this->checkcustomoption()==false){
$result = $observer->getEvent()->getResult();
$result->isAvailable = false;
return;
}
}
return;
}
public function checkcustomoption(){
//To get your cart object (in session) :
$quote = Mage::getSingleton('checkout/session')->getQuote();
//Then, to get the list of items in the cart :
$cartItems = $quote->getAllVisibleItems();
//Then, to get the count for each item :
foreach ($cartItems as $item)
{ // check $item->getProduct() give cart item
$item->getProduct();
if(your_logic_match){
return true;
break;
}
}
retrun false;
}
}
?>
for check and custom option used https://magento.stackexchange.com/questions/17867/get-custom-option-price-in-order blog Gavin answer
I created new field and included it into system.xml (Pin_Init_Block_Adminhtml_System_Robots)
Show i controled by _getElementHtml or render.
How i can catch save?
<?php
class Pin_Init_Block_Adminhtml_System_Robots extends Mage_Adminhtml_Block_System_Config_Form_Field
{
protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
{
//self::__writeRobots($element->getEscapedValue());
$html = '<textarea id="'.$element->getHtmlId().'" name="'.$element->getName()
.'" '.$element->serialize($element->getHtmlAttributes()).'>'.self::__readRobots().'</textarea>'."\n";
$html.= $element->getAfterElementHtml();
return $html;
}
protected function __readRobots( )
{
$file = fopen( Mage::getBaseDir().'/robots.txt', "r");
if(!$file) return $this->content;
$content = '';
while (!feof($file)):
$content .= fgets($file);
endwhile;
fclose($file);
return $content;
}
protected function __writeRobots( $content )
{
$file = #fopen( Mage::getBaseDir().'/robots.txt', 'w');
#fwrite($file, "$content");
}
protected function _beforeSave()
{
self::__writeRobots('text1');
}
protected function _afterSave ()
{
self::__writeRobots('text1');
}
}
?>
File: /app/code/community/Pin/Init/Block/Adminhtml/System
XML:
<robots translate="label">
<label>Robots.txt</label>
<comment></comment>
<frontend_type>text</frontend_type>
<frontend_model>init/adminhtml_system_robots</frontend_model>
<sort_order>3</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</robots>
You can specify to your element a backend_model then implement in that model the methods _afterSave and _beforeSave.
You can use as an example the web/unsecure/base_url element. It is defined in app/code/core/Mage/Core/etc/system.xml and has the backend model adminhtml/system_config_backend_baseurl.
That is equivalent to the class Mage_Adminhtml_Model_System_Config_Backend_Baseurl.
See what happens in there.
UPDATE
Make your config look like this:
<robots translate="label">
<label>Robots.txt</label>
<comment></comment>
<frontend_type>text</frontend_type>
<frontend_model>init/adminhtml_system_robots</frontend_model>
<backend_model>init/adminhtml_system_backend_robots</backend_model><!-- add this line -->
<sort_order>3</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</robots>
Now create the following class (put it in the proper file):
<?php
class Pin_Init_Block_Adminhtml_System_Backend_Robots extends Mage_Core_Model_Config_Data{
protected function _beforeSave()
{
//this is called before the value is saved
$value = $this->getValue();//this is how you can get the value
//do your magic with $value
}
protected function _afterSave()
{
//this is called after the value is saved
$value = $this->getValue();//this is how you can get the value
//do your magic with $value
}
}
Hi friends i am not expert in magento but i have some good knowledge of its themng but i dont have a very good knowledge of modules , i need to create a
custom registration form with contact info and company info
details ,
i need to create this on my own custom page , i need the magento
default registration page also
, i have check the
app\code\core\Mage\Customer\controllers/AccountController
in which i got the
public function createPostAction()
{
$session = $this->_getSession();
if ($session->isLoggedIn()) {
$this->_redirect('*/*/');
return;
}
$session->setEscapeMessages(true); // prevent XSS injection in user input
if ($this->getRequest()->isPost()) {
$errors = array();
if (!$customer = Mage::registry('current_customer')) {
$customer = Mage::getModel('customer/customer')->setId(null);
}
/* #var $customerForm Mage_Customer_Model_Form */
$customerForm = Mage::getModel('customer/form');
$customerForm->setFormCode('customer_account_create')
->setEntity($customer);
$customerData = $customerForm->extractData($this->getRequest());
if ($this->getRequest()->getParam('is_subscribed', false)) {
$customer->setIsSubscribed(1);
}
/**
* Initialize customer group id
*/
$customer->getGroupId();
if ($this->getRequest()->getPost('create_address')) {
/* #var $address Mage_Customer_Model_Address */
$address = Mage::getModel('customer/address');
/* #var $addressForm Mage_Customer_Model_Form */
$addressForm = Mage::getModel('customer/form');
$addressForm->setFormCode('customer_register_address')
->setEntity($address);
$addressData = $addressForm->extractData($this->getRequest(), 'address', false);
$addressErrors = $addressForm->validateData($addressData);
if ($addressErrors === true) {
$address->setId(null)
->setIsDefaultBilling($this->getRequest()->getParam('default_billing', false))
->setIsDefaultShipping($this->getRequest()->getParam('default_shipping', false));
$addressForm->compactData($addressData);
$customer->addAddress($address);
$addressErrors = $address->validate();
if (is_array($addressErrors)) {
$errors = array_merge($errors, $addressErrors);
}
} else {
$errors = array_merge($errors, $addressErrors);
}
}
try {
$customerErrors = $customerForm->validateData($customerData);
if ($customerErrors !== true) {
$errors = array_merge($customerErrors, $errors);
} else {
$customerForm->compactData($customerData);
$customer->setPassword($this->getRequest()->getPost('password'));
$customer->setConfirmation($this->getRequest()->getPost('confirmation'));
$customerErrors = $customer->validate();
if (is_array($customerErrors)) {
$errors = array_merge($customerErrors, $errors);
}
}
$validationResult = count($errors) == 0;
if (true === $validationResult) {
$customer->save();
Mage::dispatchEvent('customer_register_success',
array('account_controller' => $this, 'customer' => $customer)
);
if ($customer->isConfirmationRequired()) {
$customer->sendNewAccountEmail(
'confirmation',
$session->getBeforeAuthUrl(),
Mage::app()->getStore()->getId()
);
$session->addSuccess($this->__('Account confirmation is required. Please, check your email for the confirmation link. To resend the confirmation email please click here.', Mage::helper('customer')->getEmailConfirmationUrl($customer->getEmail())));
$this->_redirectSuccess(Mage::getUrl('*/*/index', array('_secure'=>true)));
return;
} else {
$session->setCustomerAsLoggedIn($customer);
$url = $this->_welcomeCustomer($customer);
$this->_redirectSuccess($url);
return;
}
} else {
$session->setCustomerFormData($this->getRequest()->getPost());
if (is_array($errors)) {
foreach ($errors as $errorMessage) {
$session->addError($errorMessage);
}
} else {
$session->addError($this->__('Invalid customer data'));
}
}
} catch (Mage_Core_Exception $e) {
$session->setCustomerFormData($this->getRequest()->getPost());
if ($e->getCode() === Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS) {
$url = Mage::getUrl('customer/account/forgotpassword');
$message = $this->__('There is already an account with this email address. If you are sure that it is your email address, click here to get your password and access your account.', $url);
$session->setEscapeMessages(false);
} else {
$message = $e->getMessage();
}
$session->addError($message);
} catch (Exception $e) {
$session->setCustomerFormData($this->getRequest()->getPost())
->addException($e, $this->__('Cannot save the customer.'));
}
}
$this->_redirectError(Mage::getUrl('*/*/create', array('_secure' => true)));
}
which is for creating new account
,
but i don't want to edit this function because i need the magento
default registration page als
o , so please suggest me how can i create a new function from where i can make the customer provide there information and can register and i can store that in database , basically i need to store the contact info and company info in address tables so that the information can be shown in admin
Your custom module should contain something similar:
Package/Module/etc/config.xml
Package/Module/controllers/contactController.php
Package/Module/sql/modulename_setup/mysql4-install-1.0.0.php
app/design/frontend/default/default/layout/customercontact.xml
config.xml:
<config>
...
<modules>
<Package_Module>
<version>1.0.0</version>
</Package_Module>
</modules>
<frontend>
<!--configure your controllers-->
<routers>
<modulename>
<use>standard</use>
<args>
<module>Package_Module</module>
<frontName>modulename</frontName>
</args>
</modulename>
</routers>
<layout>
<updates>
<modulename>
<file>customercontact.xml</file>
</modulename>
</updates>
</layout>
</frontend>
<global>
<blocks></blocks><!--you can read some blogs etc-->
<models></models><!--you can read some blogs etc-->
<helpers></helpers><!--you can read some blogs etc-->
<resources>
<modulename_setup>
<setup>
<module>Package_Module</module>
</setup>
<connection>
<use>core_setup</use>
</connection>
</modulename_setup>
<modulename_write>
<connection>
<use>core_write</use>
</connection>
</modulename_write>
<modulename_read>
<connection>
<use>core_read</use>
</connection>
</modulename_read>
</resources>
</global>
...
</config>
ContactController.php
public function customerDetailsAction(){
/*render your form
Use layout handle to set your own blocks
*/
}
public function customerDetailsPostAction(){
/*borrow some logic from AccountController or Build your own
get posted data, validate and set to model & save
*/
}
mysql4-install-1.0.0.php
Used below script in few of my similar tasks:
$installer = $this;
$installer->startSetup();
$setup = Mage::getModel('customer/entity_setup', 'core_setup');//invoke customer entity setup class
// add your attribute to customer entity
$setup->addAttribute(
'customer',
'attribute_code',
array(
'type' => 'varchar',
'input' => 'text',
'label' => 'Company name',
'global' => 1,
'visible' => 1,
'required' => 0,
'user_defined' => 1,
'visible_on_front' => 1,
)
);
if (version_compare(Mage::getVersion(), '1.6.0', '<='))
{
$customer = Mage::getModel('customer/customer');
$attrSetId = $customer->getResource()->getEntityType()->getDefaultAttributeSetId();
$setup->addAttributeToSet('customer', $attrSetId, 'General', 'attribute_code');
}
if (version_compare(Mage::getVersion(), '1.4.2', '>='))
{
/*
* To get new attribute listed for customer/form various models, example checl line 275 to 277 AccountController.php
*/
Mage::getSingleton('eav/config')
->getAttribute('customer', 'attribute_code')
->setData(
'used_in_forms',
array(
'adminhtml_customer',//will make new attribute appear in admin
'customer_account_create',//will make new attribute appear on registration
'customer_account_edit',//will make new attribute appear in account dashboard
'checkout_register'// on checkout page
)
)
->save();
}
customercontact.xml
<layout>
...
<modulename_contact_customerDetails>
<update handle="customer_account_create"/><!--if only some additional fields are needed-->
<referene name="customer_form_register"><!--set your template based on customer/form/register.phtml-->
<action method="setTemplate">path to your template</action>
</reference>
</modulename_contact_customerDetails>
...
</layout>
Hope this gives an idea of what needed to be done !
The seemingly easiest path ahead for you would be to create a custom module, with a frontend controller, a single table model and an admin grid if you wish to present the data collected by the contact form to the admin users in the way other magento modules show the data.
Creating magento extensions is quite easy if right set of tools are used, you can use this module creator to create an extension quite instantly.
As we send shippment emails to customers, in this shippment email, we get tracking number from track.phtml and now the subject part of the email is like, order number and shippment number. I would like to change the subject of the email in which we are senidng as shippment emails. The subject has to be with tracking number. For order number we can get with "order.increment_id", But I dont know how to get the tracking number. SO how can I display tracking number in subject of email?
This cannot be done only by using a variable name like "order.increment_id" in the email template. You have to send the tracking data to the email template processor to achieve this with an example in 4 steps.
Step1>> Add Module configuration
In app/etc/modules/Eglobe_Sales.xml
<?xml version="1.0"?>
<config>
<modules>
<Eglobe_Sales>
<active>true</active>
<codePool>local</codePool>
</Eglobe_Sales>
</modules>
</config>
Step2>> Add config.xml(app/code/local/Eglobe/Sales/etc/config.xml)
<?xml version="1.0"?>
<config>
<modules>
<Eglobe_Sales>
<version>0.1.0</version>
</Eglobe_Sales>
</modules>
<global>
<models>
<sales>
<rewrite>
<order_shipment>Eglobe_Sales_Model_Order_Shipment</order_shipment>
</rewrite>
</sales>
</models>
</global>
</config>
Step3>> Override Mage_Sales_Model_Order_Shipment::sendEmail()
<?php
class Eglobe_Sales_Model_Order_Shipment extends Mage_Sales_Model_Order_Shipment {
/**
* Send email with shipment data
*
* #param boolean $notifyCustomer
* #param string $comment
* #return Mage_Sales_Model_Order_Shipment
*/
public function sendEmail($notifyCustomer = true, $comment = '')
{
$order = $this->getOrder();
$storeId = $order->getStore()->getId();
if (!Mage::helper('sales')->canSendNewShipmentEmail($storeId)) {
return $this;
}
// Get the destination email addresses to send copies to
$copyTo = $this->_getEmails(self::XML_PATH_EMAIL_COPY_TO);
$copyMethod = Mage::getStoreConfig(self::XML_PATH_EMAIL_COPY_METHOD, $storeId);
// Check if at least one recepient is found
if (!$notifyCustomer && !$copyTo) {
return $this;
}
// Start store emulation process
$appEmulation = Mage::getSingleton('core/app_emulation');
$initialEnvironmentInfo = $appEmulation->startEnvironmentEmulation($storeId);
try {
// Retrieve specified view block from appropriate design package (depends on emulated store)
$paymentBlock = Mage::helper('payment')->getInfoBlock($order->getPayment())
->setIsSecureMode(true);
$paymentBlock->getMethod()->setStore($storeId);
$paymentBlockHtml = $paymentBlock->toHtml();
} catch (Exception $exception) {
// Stop store emulation process
$appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo);
throw $exception;
}
// Stop store emulation process
$appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo);
// Retrieve corresponding email template id and customer name
if ($order->getCustomerIsGuest()) {
$templateId = Mage::getStoreConfig(self::XML_PATH_EMAIL_GUEST_TEMPLATE, $storeId);
$customerName = $order->getBillingAddress()->getName();
} else {
$templateId = Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE, $storeId);
$customerName = $order->getCustomerName();
}
$mailer = Mage::getModel('core/email_template_mailer');
if ($notifyCustomer) {
$emailInfo = Mage::getModel('core/email_info');
$emailInfo->addTo($order->getCustomerEmail(), $customerName);
if ($copyTo && $copyMethod == 'bcc') {
// Add bcc to customer email
foreach ($copyTo as $email) {
$emailInfo->addBcc($email);
}
}
$mailer->addEmailInfo($emailInfo);
}
// Email copies are sent as separated emails if their copy method is 'copy' or a customer should not be notified
if ($copyTo && ($copyMethod == 'copy' || !$notifyCustomer)) {
foreach ($copyTo as $email) {
$emailInfo = Mage::getModel('core/email_info');
$emailInfo->addTo($email);
$mailer->addEmailInfo($emailInfo);
}
}
// Set all required params and send emails
$mailer->setSender(Mage::getStoreConfig(self::XML_PATH_EMAIL_IDENTITY, $storeId));
$mailer->setStoreId($storeId);
$mailer->setTemplateId($templateId);
$mailer->setTemplateParams(array(
'order' => $order,
'shipment' => $this,
'comment' => $comment,
'billing' => $order->getBillingAddress(),
'payment_html' => $paymentBlockHtml,
//setting the `track number here, A shihpment can have more than one track numbers so seperating by comma`
'tracks' => new Varien_Object(array('tracking_number' => implode(',', $this->getTrackingNumbers())))
)
);
$mailer->send();
return $this;
}
//Creating track number array
public function getTrackingNumbers()
{
$tracks = $this->getAllTracks();
$trackingNumbers = array();
if (count($tracks)) {
foreach ($tracks as $track) {
$trackingNumbers[] = $track->getNumber();
}
}
return $trackingNumbers;
}
}
Step4>> Modify your shipment email tempate subject by adding {{var tracks.track_number}}
How do I make the telephone field not required on shipping but have it required on billing in onepage checkout?
I have followed many forums that point to the below method but this disables the required element on both billing and shipping?
http://swarminglabs.com/magento-making-the-telephone-field-not-required-at-checkout/#comment-2687
I do not know any extension that would allow this. If you want to make it work you should work with Mage_Customer_Model_Form. During checkout process magento calls validateData() method of this model. This method is defined in Mage_Eav_Model_Form. You need to rewrite another model, namely Mage_Sales_Model_Quote_Address as its parent Mage_Customer_Model_Address_Abstract has a valid() method that checks if telephone is not emtpy. So, assuming you have removed is_required and validation_rules for this attribute
in a module etc/config.xml
<config>
<global>
<models>
<customer>
<rewrite>
<form>YourNamespace_YourModule_Model_Customer_Form</form>
</rewrite>
</customer>
<sales>
<rewrite>
<quote_address>YourNamespace_YourModule_Model_Quote_Address</quote_address>
</rewrite>
</sales>
</models>
</global>
</config>
in YourNamespace/YourModule/Model/Customer/Form.php
class YourNamespace_YourModule_Model_Customer_Form extends Mage_Customer_Model_Form {
public function validateData(array $data) {
//perform parent validation
$result = parent::validateData($data);
//checking billing address; perform additional validation
if ($this->getEntity()->getAddressType() == Mage_Sales_Model_Quote_Address::TYPE_BILLING) {
$valid = $this->_validatePhoneForBilling($data);
if ($result !== true && $valid !== true) {
$result[] = $valid;
}
elseif ($result === true && $valid !== true) {
$result = $valid;
}
}
return $result;
}
protected function _validatePhoneForBilling($data) {
$errors = array();
if (empty($data['telephone'])) {
$attribute = $this->getAttribute('telephone');
$label = Mage::helper('eav')->__($attribute->getStoreLabel());
$errors[] = Mage::helper('eav')->__('"%s" is a required value.', $label);
}
if (empty($errors)) {
return true;
}
return $errors;
}
}
in YourNamespace/YourModule/Model/Quote/Address.php
class YourNamespace_YourModule_Model_Quote_Address extends Mage_Sales_Model_Quote_Address {
public function validate() {
if ($this->getAddressType() == self::TYPE_SHIPPING) {
$result = parent::validate();
$errorMsg = Mage::helper('customer')->__('Please enter the telephone number.');
if (is_array($result) && in_array($errorMsg, $result)) {
$result = array_diff($result, array($errorMsg));
}
if (empty($result)) {
return true;
}
return $result;
}
else {
return parent::validate();
}
}
}