Magento doesn't save value on 'save' - magento

I have a custom module that adds a field to an element in
<?php
class NS_MN_Block_Cms_Page_Edit_Tab_Main extends Mage_Adminhtml_Block_Cms_Page_Edit_Tab_Main
{
public function _prepareForm()
{
parent::_prepareForm();
$fieldset = $this->getForm()->getElements()->searchById('base_fieldset');
$fieldset->addField('bar', 'text',
array(
'label' => Mage::helper('cms')->__('BaR'),
'class' => 'input-text',
'name' => 'bar',
'required' => false
)
);
return $this;
}
}
I have added the bar field into the cms_page table and the field is rendered, but when I save the cms page, the field is not saved to the database.
Could anyone tell me what I am overlooking here?

You need to remember to flush your cache. This one has caught me out a few times before.
Go into System > Cache Management and click both flush buttons.
Log out of the admin and log back in. Everything should function as expected.

Have you added the field to the database? Having the field in the form is one step, but in order to persist the data it must be able to live in a column in the DB. Once the field is in the DB, you might have to change the controller to recognize the new field, but it might already work for all fields. If it is already doing a setData($data) where $data is all received form data, you should be fine.

Related

Magento rewrite an existing form and update an existing field

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);

Change Magento product's attribute set.

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 :)

Magento New Cart Attribute

Hi well the problem I am facing seemed to be very simple at first but turned into a real nightmare now.
I was asked to add an attribute (namely point) to all the products (which was done pretty simple using the admin panel) and have its total as a cart attribute which rules can be set upon!?
I am quite positive that cart attributes are defined in:
class Mage_SalesRule_Model_Rule_Condition_Address extends Mage_Rule_Model_Condition_Abstract
{
public function loadAttributeOptions()
{
$attributes = array(
'base_subtotal' => Mage::helper('salesrule')->__('Subtotal'),
'total_qty' => Mage::helper('salesrule')->__('Total Items Quantity'),
'weight' => Mage::helper('salesrule')->__('Total Weight'),
'payment_method' => Mage::helper('salesrule')->__('Payment Method'),
'shipping_method' => Mage::helper('salesrule')->__('Shipping Method'),
'postcode' => Mage::helper('salesrule')->__('Shipping Postcode'),
'region' => Mage::helper('salesrule')->__('Shipping Region'),
'region_id' => Mage::helper('salesrule')->__('Shipping State/Province'),
'country_id' => Mage::helper('salesrule')->__('Shipping Country'),
);
$this->setAttributeOption($attributes);
return $this;
}
<...>
So if I overwrite this model and add an item to that array I will get the attribute shown in rule definition admin panel. It seems that all these attributes has a matching column in sales_flat_quote_address table except for total_qty and payment_method!
Now the problem is what should I do to have my new attribute be calculated and evaluated in rules processing? should I add a column to this table and update its value upon cart changes?
Any insight on how to do this would be of great value thanks.
I finally managed to accomplish the task and just for future reference I explain the procedure here.
The class mentioned in the question (ie: Mage_SalesRule_Model_Rule_Condition_Address) is the key to the problem. I had to rewrite it and for some odd reason I couldn't get what I needed by extending it so my class extended its parent class (ie: Mage_Rule_Model_Condition_Abstract).
As I said I added my attribute to $attributes like this:
'net_score' => Mage::helper('mymodule')->__('Net Score')
I also modified getInputType() method and declared my attribute as numeric
now what does the trick is the validate() method:
public function validate(Varien_Object $object)
{
$address = $object;
if (!$address instanceof Mage_Sales_Model_Quote_Address) {
if ($object->getQuote()->isVirtual()) {
$address = $object->getQuote()->getBillingAddress();
}
else {
$address = $object->getQuote()->getShippingAddress();
}
}
if ('payment_method' == $this->getAttribute() && ! $address->hasPaymentMethod()) {
$address->setPaymentMethod($object->getQuote()->getPayment()->getMethod());
}
return parent::validate($address);
}
as you can see it prepares an instance of Mage_Sales_Model_Quote_Address and sends it to its parent validate method. you can see that this object ($address) does not have payment_method by default so this method creates one and assigns it to it. So I did the same, simply I added the following code before the return:
if ('net_score' == $this->getAttribute() && ! $address->hasNetScore()) {
$address->setNetScore( /*the logic for retrieving the value*/);
}
and now I can set rules upon this attribute.
Hope that these information saves somebody's time in the future.

How to insert a user in the database only if there is no email address using the zend framework?

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
))

Why does my data not pass into my view correctly?

I have a model, view and controller not interacting correctly, and I do not know where the error lies.
First, the controller. According to the Code Igniter documentation, I'm passing variables correctly here.
function view() {
$html_head = array( 'title' => 'Estimate Management' );
$estimates = $this->Estimatemodel->get_estimates();
$this->load->view('html_head', $html_head);
$this->load->view('estimates/view', $estimates);
$this->load->view('html_foot');
}
The model (short and sweet):
function get_estimates() {
$query = $this->db->get('estimates')->result();
return $query;
}
And finally the view, just to print the data for initial development purposes:
<? print_r($estimates); ?>
Now it's undefined when I navigate to this page. However, I know that $query is defined, because it works when I run the model code directly in the view.
$estimates = $this->Estimatemodel->get_estimates();
$this->load->view('estimates/view', $estimates);
You're loading the return of $this->Estimatemodel->get_estimates() as the array of view variables. In other words, all the children of $estimates (assuming it can be treated as an array) are available in your view. But not the parent element.
The key here is when loading a view the second parameter needs to be an array of values, not just a single value.
$this->load->view('estimates/view', array('estimates' => $estimates));
That should get the result you're looking for, in fact, you're already doing that for the html header view. Even though that view only has one variable, it's passed as the single element of an array:
$html_head = array( 'title' => 'Estimate Management' );
$this->load->view('html_head', $html_head);
The documentation shows that the object you pass to the view must be an associative array.
$data = array(
'estimates' => $estimates
);
$this->load->view('estimates/view', $data);
Docs here

Resources