I want to update an existing form in Magento backend. Because I don't want to touch the original extension I copied the file and rewrote the class:
class Bleedo_xta_Block_Adminhtml_xta_Edit_Tab_information extends Hedox_xta_Block_Adminhtml_xta_Edit_Tab_information {
protected function _prepareForm() {
parent::_prepareForm();
$form = $this->getForm();
This works (if you found this article via Google, don't forget to insert this rewrite in your config.xml)
If I want to add a new field to this form you can easily do this by
$options = $form->getElement('options_form');
$options->addField('new_cost', 'text', array(
'name' => 'new_cost',
'label' => $this->__('New Cost'),
));
But how can I update an existing field? The problem is that I want to set an already existing field to "required". But if I'm using addField I get an error.
Thank you so much!
/* #var $elm Varien_Data_Form_Element_Text */
$elm = $this->getForm()->getElement('new_cost');
$elm->setData('required',1);
Related
I'm writing a custom Magento module for my store and I'm facing a weird issue with a fieldset in one form. The form is assigned to a tab, however the fieldset starts from the top of container, not from just below buttons area. Please see the image attached
I want it to display like:
This module is being developed on Magento 1.9.0.1 without any modification whatsoever, just the demo data.
Below is the code for all the classes:
Controller:
added form container and tabs to left column
class Koala_Socialmanager_Adminhtml_TwitterController extends Mage_Adminhtml_Controller_Action {
public function directTweetAction(){
$this->loadLayout();
$this->_addContent($this->getLayout()->createBlock('koala_socialmanager/twitter_directTweet_tweet','directTweet'))
->_addLeft($this->getLayout()->createBlock('koala_socialmanager/twitter_directTweet_edit_tabs'));
$this->renderLayout();
Form container:
class Koala_Socialmanager_Block_Twitter_DirectTweet_Tweet extends Mage_Adminhtml_Block_Widget_Form_Container {
public function __construct()
{
$this->_blockGroup = 'koala_socialmanager';
$this->_controller = 'twitter_directTweet';
$this->_headerText = Mage::helper('koala_socialmanager')->__('Direct Tweets');
parent::__construct();
$this->_updateButton('save', 'label', Mage::helper('adminhtml')->__('Tweet Now!'));
}
}
Tabs:
class Koala_Socialmanager_Block_Twitter_DirectTweet_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs{
public function __construct(){
parent::__construct();
$this->setId('tweetTabs');
$this->setDestinationElementId('edit_form');
$this->setTitle(Mage::helper('koala_socialmanager')->__('Twitter'));
}
public function _beforeToHtml(){
$this->addTab('form_section_form',array(
'label' => Mage::helper('koala_socialmanager')->__("Tweet"),
'title' => Mage::helper('koala_socialmanager')->__("Tweet"),
'content' => $this->getLayout()->createBlock('koala_socialmanager/twitter_directTweet_edit_tabs_form')->initForm()->toHtml(),
'active' => true
));
$this->addTab('form_section_external_media',array(
'label' => Mage::helper('koala_socialmanager')->__("External Media"),
'title' => Mage::helper('koala_socialmanager')->__("External Media"),
'content' => $this->getLayout()->createBlock('koala_socialmanager/twitter_directTweet_edit_tabs_externalMedia')->initForm()->toHtml()
));
$this->addTab('form_section_magento_media',array(
'label' => Mage::helper('koala_socialmanager')->__("Magento Product Media"),
'title' => Mage::helper('koala_socialmanager')->__("Magento Product Media"),
'content' => $this->getLayout()->createBlock('koala_socialmanager/twitter_directTweet_edit_tabs_magentoProductMedia')->toHtml()
));
return parent::_beforeToHtml();
}
}
And form with fieldset:
class Koala_Socialmanager_Block_Twitter_DirectTweet_Edit_Tabs_Form extends Mage_Adminhtml_Block_Widget_Form {
public function __construct()
{
parent::__construct();
}
public function initForm(){
$form = new Varien_Data_Form();
$this->setForm($form);
$form->setHtmlIdPrefix('socialmanager');
$helper = Mage::helper('koala_socialmanager');
$fieldset = $form->addFieldset('base_fieldset', array(
'legend' => Mage::helper('koala_socialmanager')->__('Tweeter Message')
));
$fieldset->addField('statusUpdate', 'textarea', array(
'name'=>'tweet',
'label'=>$helper->__("Tweet this Message:"),
'after_element_html'=>'<div class="characterCounter">0</div>'
));
Mage::helper('koala_socialmanager')->getTwitterFormScript();
return $this;
I believe I'm missing something silly. Any help appreciated.
Cheers
Paul
I've solved the problem, still don't know the cause though. I simply rewritten everything to another folder changing the class names, created another action in controller called testAction, so all files from DirectTweet folder are located in Message folder, and guess what? when you display that form from testActoin it works as it should, when I display the old form from DirectTweet folder - fieldset is broken.
I have magento cache disabled all the time, I cleared all tmp, cache, session folders, cleared browser cache and had no luck with fixing it, so I'm wondering why the new "version" works even though there is no changes to the code apart from cosmetic ones (removing empty lines, or changed text for labels/headers).
For the last 20 minutes I was comparing file by file in phpstorm, and seriously no differences apart from class names and texts to output.... I'm to tired to think about it anymore.
Below desired output :)
Happy New Year
Paul
I would like to add custom variable on new order email notification having value populated from table sales_flat_order (i.e. heared4us ). How can I do this ?
I am using magento version 1.7.0.2
Thanks.
To add new fields to order e-mail you need to follow the following 2 steps
1) Edit sendNewOrderEmail() function located in
app/code/core/Mage/Sales/Model/Order.php
In that function you will find following code
$mailer->setTemplateParams(array(
'order' => $this,
'billing' => $this->getBillingAddress(),
'payment_html' => $paymentBlockHtml,
));
You need to add new key value pair to add new custom value
$mailer->setTemplateParams(array(
'order' => $this,
'billing' => $this->getBillingAddress(),
'payment_html' => $paymentBlockHtml,
'customvalue' => 'This is a custom value' //New custom value
));
2) Now the second part. You need to add the custom variable to new order email template.
Just edit the template add your custom parameter name. in the example it is "customvalue".
{{ var customvalue }}
For English the order e-mail template is located in
app\locale\en_US\template\email\sales\order_new.html
app\locale\en_US\template\email\sales\order_new_guest.html
So depending on your language used in the website select the proper template located inside locale folder.
Also you can edit the e-mail template from admin by navigating to
System > Transactional Emails > New Order Email
public function execute(\Magento\Framework\Event\Observer $observer) {
$transport = $observer->getEvent()->getTransport();
$transportObj = $observer->getData('transportObject');
/** #var \Magento\Framework\App\Action\Action $controller*/
$transport = $observer->getTransport();
$transportObj->setData('custom_content',"custom content 123");
return $transportObj;
}
I have started using magento as my ecommerce cms and I know that is an extremely powerful platform.
Recently I came across its functionality that helps the developer extending the core and I have managed to add custom category options.
Is there any chance to achieve the same results on an attribute?
I would like to add a text description on the properties' tab and display it on the front end?
This is possible with writing your own custom module. I did it to add a tooltip-option to an attribute.
You can use the adminhtml_catalog_product_attribute_edit_prepare_form-event to add a field with your observer:
$fieldset = $observer->getForm()->getElement('base_fieldset');
$fieldset->addField('tooltip', 'text', array(
'name' => 'tooltip',
'label' => Mage::helper('catalog')->__('Tooltip'),
'title' => Mage::helper('catalog')->__('Tooltip')
));
This adds the extra field to the attribute-edit screen. Next up is to make sure the property gets saved when editing your attribute. This can be done in your installer script with something like:
$installer->getConnection()->addColumn(
$installer->getTable('catalog/eav_attribute'),
'tooltip',
array(
'type' => Varien_Db_Ddl_Table::TYPE_TEXT,
'nullable' => true,
'comment' => 'Tooltip'
)
);
You also have to make sure your Model/Resource/Setup-class extends Mage_Eav_Model_Entity_Setup instead of Mage_Core_Model_Resource_Setup.
Now, at this point, you can save your custom attribute property. Next step is to display it on the frontend. This can be done fairly easy, just by simple Magento templating 101:
For example, in catalog/product/view/type/options/configurable.phtml in the foreach()-loop, place something like this, to display the tooltip:
echo $_attribute->getProductAttribute()->getTooltip();
That's nice...
Update: Since I got some questions about this subject by e-mail, I decided to write a more detailed blog post about it. You can read it here: http://gielberkers.com/add-custom-properties-magento-attributes/
For Magento 2
(Adding simple Yes/No property for product attributes).
It could be used ui_component "product_attribute_add_form.xml" (example could be find in vendor modules)
OR if it is not working:
Create a new module Vendor_ModuleName. Extend "catalog_eav_attribute" and add new column in Vendor/ModuleName/etc/db_schema.xml (don't forget to generate db_schema_whitelist.json)
<?xml version="1.0"?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
<table name="catalog_eav_attribute">
<column xsi:type="smallint" name="new_column" padding="6" unsigned="false" nullable="false"
identity="false" default="0" comment="Comment for new_column"/>
</table>
</schema>
Subscribe on event in Vendor/ModuleName/etc/adminhtml/events.xml
"product_attribute_form_build_main_tab" - if you want to put a new property in main tab (base_fieldset)
"product_attribute_form_build" - if you want to put a new property in advanced tab (advanced_fieldset)
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="product_attribute_form_build">
<observer
name="vendor_modulename_observer_backend_product_attributeformbuild"
instance="Vendor\ModuleName\Observer\Backend\Product\AttributeFormBuild"/>
</event>
</config>
Create an observer Vendor/ModuleName/Observer/Backend/Product/AttributeFormBuild.php
<?php
declare(strict_types=1);
namespace Vendor\ModuleName\Observer\Backend\Product;
use Magento\Framework\Module\Manager;
use Magento\Config\Model\Config\Source\Yesno;
class AttributeFormBuild implements \Magento\Framework\Event\ObserverInterface
{
protected Yesno $yesNo;
protected $moduleManager;
/**
* #param Manager $moduleManager
* #param Yesno $yesNo
*/
public function __construct(
Manager $moduleManager,
Yesno $yesNo
)
{
$this->moduleManager = $moduleManager;
$this->yesNo = $yesNo;
}
/**
* #param \Magento\Framework\Event\Observer $observer
* #return void
*/
public function execute(
\Magento\Framework\Event\Observer $observer
) {
if (!$this->moduleManager->isEnabled('Vendor_ModuleName')) {
return;
}
$form = $observer->getForm();
// $fieldset = $form->getElement('base_fieldset');
$fieldset = $form->getElement('advanced_fieldset');
$yesnoSource = $this->yesNo->toOptionArray();
$fieldset->addField(
'new_column',
'select',
[
'name' => 'new_column',
'label' => __('New column label'),
'title' => __('New column title'),
'note' => __('Use this attribute for something'),
'values' => $yesnoSource,
'required' => false,
],
'is_filterable'
);
}
}
I want to change the attribute set of Magento. I searched through, and everyone suggested to delete the product and re-import it with new attribute set.
I did the same however after importing the data I could not see product reviews and associated blog post with product.
Can anyone tell me is it possible to get product reviews and associated blog post after re-importing the product with new attribute set.
Once set you can't change the attribute set of a product. But it's possible using this module so you don't have to reimport your data
https://marketplace.magento.com/flagbit-magento-changeattributeset.html
It's also possible to change the attribute set directly in the database.
Look up the attribute set ID in table eav_attribute_set
Change the attribute set ID in catalog_product_entity
Of course, be careful when changing data this way.
It is fiddly to do and a bit messy:
Make sure new attribute set is set up
Export the products you want to change
Delete the products that you are changing on the site
Change the attribute set on the downloaded file
Import changed file again
Open each changed product, set their attribute values, save it
Or do what I do, install this great extension from Amasty http://amasty.com/mass-product-actions.html - it makes changing a breeze and gives many more time saving and enhancing options.
Once you delete the product you can't get the old review.
You don't need to delete the product . You can change the attribute set by editing and use.
other wise create a new attribute set and create new product.
Yes. We can change product attribute set programmatically.
I prefer to create massaction in catalog product grid to multiselect product and then select massaction for the products.
Creating massaction in grid.php
$sets = Mage::getResourceModel('eav/entity_attribute_set_collection')
->setEntityTypeFilter(Mage::getModel('catalog/product')->getResource()->getTypeId())
->load()
->toOptionHash();
$this->getMassactionBlock()->addItem('changeattributeset', array(
'label'=> Mage::helper('catalog')->__('Change attribute set'),
'url' => $block->getUrl('*/*/changeattributeset', array('_current'=>true)),
'additional' => array(
'visibility' => array(
'name' => 'attribute_set',
'type' => 'select',
'class' => 'required-entry',
'label' => Mage::helper('catalog')->__('Attribute Set'),
'values' => $sets
)
)
));
Creating controller action for change attribute sets of the selected products.
public function changeattributesetAction()
{
$productIds = $this->getRequest()->getParam('product');
$storeId = (int)$this->getRequest()->getParam('store', 0);
if (!is_array($productIds)) {
$this->_getSession()->addError($this->__('Please select product(s)'));
} else {
try {
foreach ($productIds as $productId) {
$product = Mage::getSingleton('catalog/product')
->unsetData()
->setStoreId($storeId)
->load($productId)
->setAttributeSetId($this->getRequest()->getParam('attribute_set'))
->setIsMassupdate(true)
->save();
}
Mage::dispatchEvent('catalog_product_massupdate_after', array('products'=>$productIds));
$this->_getSession()->addSuccess(
$this->__('Total of %d record(s) were successfully updated', count($productIds))
);
}
catch (Exception $e) {
$this->_getSession()->addException($e, $e->getMessage());
}
}
$this->_redirect('adminhtml/catalog_product/index/', array());
}
You can add to your data patch apply function something like this:
public function apply(): self
{
$this->moduleDataSetup->getConnection()->startSetup();
/** #var EavSetup $eavSetup */
$eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
$eavSetup->addAttributeToSet(
Product::ENTITY,
'Default',
'General',
CustomAttributesInterface::ATTRIBUTE_CODE_MANUFACTURER
);
$this->moduleDataSetup->getConnection()->endSetup();
return $this;
}
This changes the manufacturer products attribute to the Default attribute set. (By default this attribute has no attribute set.)
Hope it helps :)
I have my controller, my function to insert into the database, and the form.
I just want to insert the user in the database if he enter the email is not already registered in the database.
My controller:
$nome = $this->_request->getParam('nome');
$senha = $this->_request->getParam('senha');
$confirmar = $this->_request->getParam('confirmar');
$email = $this->_request->getParam('email');
$usuarios = new Application_Model_DbTable_Usuarios();
$usuarios->addUsuario($nome, $senha, $email);
My DbTable_Usuario class that contains my function that inserts the user in the database
public function addUsuario($nome, $senha, $email) {
$data = array(
'id' => 'NULL',
'nome' => $nome,
'senha' => $senha,
'email' => $email,
'nivel' => '0'
);
$this->insert($data);
}
And my zend_form
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email:')
->setRequired(true)
->addValidator('EmailAddress')
->addValidator('NotEmpty');
I have some way to add something to the form it checks if the mail entered already exists in the database? If it exists, it displays the message, and if not, insert it in the bank.
Add a Zend_Validate_Db_NoRecordExists validator to the email field.
To give a closer insight on a specific problem using NoRecordExists. The Validator is added just at the way that other validators are
$email->addValidator('Db_NoRecordExists', false, array('table'=>'usario', 'field'=>'email'));
Depending on your form setup, you will use the exact same field for EDITING a user, too. When editing a user the NoRecordExists is a little tricky. As for once, you shouldn't be allowed to change into an existing email, but you should be able to update your other data and keep your email (which though is existing in your db in the current row).
You therefore need to remove the current row from that rule. There are several approaches, which you can see from my own question, but i think the following works best from controller level:
$form = new UserForm();
$form->getElement('email')->getValidator('Db_NoRecordExists')->setExclude(array(
'field' => 'id',
'value' => $idToEdit
))