Magento registration with Billing & Shipping address - magento

Is it possible that when user register in Magento, that time he also saves his Addresses (Billing & Shipping)

Create a module with a controller that extends the Mage_Customer_AccountController, containing createPostAction(). I duplicated the bit that handles the billing address, find this if-block:
if ($this->getRequest()->getPost('create_address')) {
And add this to the end of it:
if ($this->getRequest()->getPost('create_shipping_address')) {
$shippingAddress = Mage::getModel('customer/address');
$shippingAddressForm = Mage::getModel('customer/form');
$shippingAddressForm->setFormCode('customer_register_address')
->setEntity($shippingAddress);
$shippingAddressData = array(
'firstname' => $addressData['firstname'],
'lastname' => $addressData['lastname'],
'company' => $this->getRequest()->getPost('shipping_company'),
'street' => $this->getRequest()->getPost('shipping_street'),
'city' => $this->getRequest()->getPost('shipping_city'),
'country_id' => $this->getRequest()->getPost('shipping_country_id'),
'region' => $this->getRequest()->getPost('shipping_region'),
'region_id' => $this->getRequest()->getPost('shipping_region_id'),
'postcode' => $this->getRequest()->getPost('shipping_postcode'),
'telephone' => $this->getRequest()->getPost('shipping_telephone'),
'fax' => $this->getRequest()->getPost('shipping_fax')
);
$shippingAddressErrors = $addressForm->validateData($shippingAddressData);
if ($shippingAddressErrors === true) {
$shippingAddress->setId(null)
->setIsDefaultBilling($this->getRequest()->getParam('shipping_default_billing', false))
->setIsDefaultShipping($this->getRequest()->getParam('shipping_default_shipping', false));
$shippingAddressForm->compactData($shippingAddressData);
$customer->addAddress($shippingAddress);
$shippingAddressErrors = $shippingAddress->validate();
if (is_array($shippingAddressErrors)) {
$errors = array_merge($errors, $shippingAddressErrors);
}
} else {
$errors = array_merge($errors, $shippingAddressErrors);
}}
Of course you also need to duplicate the form in your themes template/customer/form/register.html, specifically the code inside this if-block:
if($this->getShowAddressFields()): ?>
Prefix all the field names IDs and in the copied code with shipping_. In the JavaScript at the bottom you need to duplicate the RegionUpdater line, like so:
new RegionUpdater('country', 'region', 'region_id', <?php echo $this->helper('directory')->getRegionJson() ?>, undefined, 'zip');
new RegionUpdater('country', 'shipping_region', 'shipping_region_id', <?php echo $this->helper('directory')->getRegionJson() ?>, undefined, 'zip');
(almost) complete code can be found here:
AccountController.php:
http://pastebin.com/9h9HqYAa
register.html:
http://pastebin.com/Q7EawU7L
It works perfectly

There is a way you can have one address input while registration.
Go to : template/customer/form/register.phtml and if($this->getShowAddressFields())
Just forcefully alter this condition and you will get address fields there.

To add to Massi and Steve's answer, in Magento 1.9.0.1, I am just learning but I was able to get this to work by adding that code to the end of _getErrorsOnCustomerAddress function in an extension of Mage_Customer_AccountController.

Not in the default magento version. you must search for an extension for this or write your own "observer" to add an address on the same time of the registration.

Like butcher said,adding that code to the end of _getErrorsOnCustomerAddress. I just tried it, and it works fine for me.
And I also set the value for "1" instead of "0" in the code
<input type="hidden" name="create_shipping_address" value="0" />
(look the link that Steve and Massi have given register.html: http://pastebin.com/Q7EawU7L)
Im on Magento 1.9.0.1

Related

Set Product Custom Options From Observer Magento 1.9

I am trying to add custom options to products on save. I want to add or update custom options (not additional options) on before_product save. I am able to access the observer and it is working on save as well but unable to update the custom options. Create option code is working if run from standalone script but not from observer only.
This is my observer code
`class Company_Module_Model_Observer{
public function updateOptions($observer){
$product = $observer->getEvent()->getProduct();
$categories= $product->getCategoryIds();
$currentCategory = '';
foreach ($categories as $cat_id){
$cat = Mage::getModel('catalog/category')->load($cat_id);
$currentCategory = $cat->getName();
}
$skuList =['LAPTOP_','DESKTOP_'];
$upgrades = $optionValues = [];
if($currentCategory=='Laptops'){
$_productCollection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToFilter('sku', array('like' => 'LAPTOP_%'));
$upgrades = $_productCollection;
}
$meta = "6 this is product meta with custom plugin ".$product->getName();
foreach ($upgrades as $products) {
$_product = Mage::getModel('catalog/product')->load($products->getId());
$optionValues = array(
'title' => $_product->getName(),
'price' => $_product->getPrice(),
'price_type' => 'fixed',
'sku' => $_product->getSku(),
'sort_order' => 0,
);
}
$options = array(
'title' => 'Upgrades',
'type' => 'drop_down',
'is_required' => 0,
'sort_order' => 0,
'values' => $optionValues
);
$product->setMetaDescription($meta);
$product->setProductOptions(array($options));
$product->setCanSaveCustomOptions(true);
//if uncomment this then save loop continues and site hangs
//$product->save();
}
}`
No error in logs or anything else. Please guide me how I can achieve this.
You are in an infinite loop because the observer relaunches the same function each time, so when you run the save product function ( $product->save(); ), your function is rerun, and so on.
If you use the event catalog_product_save_before observer, you don't have to run the save function.
otherwise here:
foreach ($categories as $cat_id){
$cat = Mage::getModel('catalog/category')->load($cat_id);
$currentCategory = $cat->getName();
}
You get the last category in the collection, is that correct?
I know this is a bit late, but I had a similar issue like this a while back...
You are calling $product->setProductOptions() which without knowing your code I can only guess is setting it on the $product's _data array, which is probably not what you want. You need to stick it on the $product's option instance which will be used during the $product->_afterSave() call (You can see where the custom options are being saved in Mage_Catalog_Model_Product _afterSave() (~line 554 as of 1.9.4.5)). You can get the option instance like this: $optionInstance = $product->getOptionInstance() and set your options like this: $optionInstance->addOption($options). After you do that you should be able to allow the save to continue and your custom options should be created.

core/html_select set aria-selected Magento 1

I'm searching for a solution with the magento buildin way to create html select blocks, with aria-required. I can display basic attributes like the id or the class for example, but not this attribute.
Here is bellow my two essay:
my first essay:
$select = Mage::app()->getLayout()->createBlock('core/html_select');
$select->setName($name)
->setClass($class)
->setId($id);
->setArialRequired($ariaRequired); //doesn't work
my second essay:
$select = Mage::app()->getLayout()->createBlock('core/html_select');
$select->setData(array(
'name' => $name,
'class' => $class,
'id' => $id,
'aria-required' => $ariaRequired //doesn't work
));
I expect the aria-required="true", but i have nothing.
Here is the solution :
->setExtraParams('aria-required=true');

Validate Select2 in Yii2 via AJAX

I have Yii2 application which uses the Kartik plugin to initialize Select2 dropdowns in forms.
I have one particular Select2 which uses AJAX call to get the data for the drop down options.
<?=
$form->field($model, 'court_house_id', ['enableAjaxValidation' => true, 'selectors' => ['input' => '#' . $id . "-court-house"],'template' => FormHelper::GenerateFieldTemplate([6])])
->widget(Select2::classname(), [
'options' => ['id' => $id . "-court-house", 'placeholder' => Yii::t('app', 'Search court house...')],
'hashVarLoadPosition' => \yii\web\View::POS_READY,
'pluginOptions' => [
'dropdownParent' => new JsExpression("$('#$modalWindowId')"),
'allowClear' => true,
'minimumInputLength' => 2,
'language' => [
'errorLoading' => new JsExpression("function () { return '" . Yii::t('app', 'Search...') . "'; }"),
],
'ajax' => [
'url' => app\components\UrlMaker::link('data/court-house-list'),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(courthouse) { return courthouse.text; }'),
'templateSelection' => new JsExpression('function (courthouse) { return courthouse.text;}'),
]])
->label(Yii::t('app', 'Court House'), ['class' => FormHelper::GenerateLabelClassTemplate([3])]);
?>
Intentionally pasting all of the code, although most of it is irrelevant I would assume.
I have this loaded in multiple dynamically created forms thus all the strange ids and selectors. However, the form has different dropdown which controls whether some of the fields are shown (and required) or not. This particular field above is only shown in one of the scenarios which all the other variations of the form do not have it. So the model has the following validation:
[['court_house_id', 'staff'], 'required', 'on' => self::SCENARIO_ONE],
By the way staff is just a regular text field and everything works for it.
In order to change the scenario, I have the following line in the view with the form:
<?php $model->scenario = \app\models\MyModel::SCENARIO_ONE; ?>
The problem is that when I submit the form empty, the staff field gets marked in red as invalid but the court house is marked in green as valid although it is empty.
If I go into the model and remove the 'on' => self::SCENARIO_ONE part then everything works as expected - on empty submit the court house field also lights up in red but that would be a problem for the rest of my scenarios where this field is not needed.
Any ideas what might be causing the problem and how to resolve it?
Try to set the scenario in controller before calling save() method, for example
$model = new MyModel(['scenario' => MyModel::SCENARIO_ONE])

Codeigniter ion auth user management while create a new user

Hope you guys are fine. I am in a little problem. I am not expert in Codeigniter.
I have 5 user groups like super_admin, admin, reseller, agent and general. while super_admin will create a user he can give all access to the new user. but an admin can give reseller, agent and general. Reseller can agent and general and finally agent cant only general access. Now want to hide those user group name from a drop-down menu which has not permission of a user.
My code is below. I wrote the code in a create_user.php page. Please help me.
<?php
foreach ($groups as $group):
$a=$this->ion_auth->get_users_groups()->row()->name;
if(!in_array($group->name, $a)){
?>
<option value="<?php echo $group['id']; ?>"><?php echo htmlspecialchars($group['description'], ENT_QUOTES, 'UTF-8'); ?></option>
<?php } endforeach ?>
</select>
</div>
?php endif ?>
Here is an example that you can test.
Few assumptions are taken that should be readily apparent like consecutive ids and that super_admin is id 5.
The relevant ion_auth functions are commented out.
<?php
$groups = array(
array(
'id' => 1,
'name' => 'general'
),
array(
'id' => 2,
'name' => 'agent'
),
array(
'id' => 3,
'name' => 'reseller'
),
array(
'id' => 4,
'name' => 'admin'
),
array(
'id' => 5,
'name' => 'super_admin'
),
);
//$groups = $this->ion_auth->groups()->result_array();
array_pop($groups); // remove super_admin (last element) from array
$curr_user_group = 4;
//$curr_user_group = $this->ion_auth->get_users_groups()->row()->id;
$user_create_groups = $curr_user_group - 1;
$groups = array_slice($groups, 0, $user_create_groups);
echo '<pre>';
foreach ($groups as $group) {
print_r($group);
}
As general can't create a group lower the $groups array will be blank for it. Hopefully you have thought of this and have some system in place so a user with that group can't create users. Also note that you need to institute a similar validation function on the backend to make sure users don't elevate themselves or others to super_admin by changing the select box in their browser.

Magento controller url redirects to dashboard

Basically in trying to create an inbox message which "read details" should redirect the user to a custom controller, however i can see the desired url in the browser for a second and then it redirects to the dashboard; this is how, currently, im trying to achieve that:
$myId = $myJson['id'];
$title = "Title of my notice";
$description = $myJson['text'];
$url= Mage::helper("adminhtml")->getUrl('My_Module/Controller/index', array('id' => $myId));
$sendingMessage = Mage::getModel('adminnotification/inbox')->addNotice($title,$description,$url);
The code above successfully adds the message to the inbox, however as i said before, i can see the desired URL in the browser before it gets redirected to the dashboard.
I'm accessing the same controller from another one and it does it as expected, the one that is actually working is a Grid and it looks something like this:
$this->addColumn('action',
array(
'header' => __('Answer'),
'width' => '100',
'type' => 'action',
'getter' => 'getId',
'actions' => array(
array(
'caption' => __('Answer'),
'url' => array('base'=> '*/Controller'),
'field' => 'id'
)),
'filter' => false,
'sortable' => false,
'index' => 'stores',
'is_system' => true,
));
So, am i missing something here ?
BTW, is there any way to make the "read details" link to open in the same page instead of a new tab?
==================================================================
UPDATE
Disabling the "Add Secret Key to URLs" in the security options allowed me get it work, however i would like to make use of the secret keys.
The URLs i'm generating in the first code block actually have a key/value in the URLs, they look something like this:
https://example.com/index.php/mymodule/Controller/index/id/3963566814/key/f84701848a22d2ef36022accdb2a6a69/
It looks like you're trying to generate an admin URL. In modern versions of Magento, admin urls must use the adminhtml front name, using the Magento Front Name Sharing technique (described in this article). That's must as in if you don't, the URLs won't work. Magento removed the ability to create non-adminhtml URLs in the backend.
Second, here's where Magento generates the secret keys
#File: app/code/core/Mage/Adminhtml/Model/Url.php
public function getSecretKey($controller = null, $action = null)
{
$salt = Mage::getSingleton('core/session')->getFormKey();
$p = explode('/', trim($this->getRequest()->getOriginalPathInfo(), '/'));
if (!$controller) {
$controller = !empty($p[1]) ? $p[1] : $this->getRequest()->getControllerName();
}
if (!$action) {
$action = !empty($p[2]) ? $p[2] : $this->getRequest()->getActionName();
}
$secret = $controller . $action . $salt;
return Mage::helper('core')->getHash($secret);
}
and here's where it validates the secret key
#File: app/code/core/Mage/Adminhtml/Controller/Action.php
protected function _validateSecretKey()
{
if (is_array($this->_publicActions) && in_array($this->getRequest()->getActionName(), $this->_publicActions)) {
return true;
}
if (!($secretKey = $this->getRequest()->getParam(Mage_Adminhtml_Model_Url::SECRET_KEY_PARAM_NAME, null))
|| $secretKey != Mage::getSingleton('adminhtml/url')->getSecretKey()) {
return false;
}
return true;
}
Compare the pre/post hash values of $secret to see why Magento's generating the incorrect key on your page.

Resources