I have added an extra field in the admin_role table in magento called limit_products. I have also added an extra field into the magento backend, and using the admin_permissions_role_prepare_save event I set this field to either 1 or 0, using the function below. However, it doesn't seem to want to save this field at all. Any ideas what I am doing wrong? I even tried setting the field in RoleController.php (where the other fields are set), but no luck. Anyone know what I'm doing wrong?
public function adminPermissionsRolePrepareSave(Varien_Event_Observer $observer) {
$role = $observer->getEvent()->getObject();
$request = $observer->getEvent()->getRequest();
//fb($request);
$role->setLimitProducts((bool)$request->getPost('limit_products', false));
return $this;
}
EDIT: I just realised I forgot to mention that $request->getPost('limit_products', false); does return the right value, it's just the $role->setLimitProducts(); isn't saving it. Also when I do $role->getLimitProducts(); it does return the right value.
Related
If you are thinking this question is a beginner's question, maybe you are right. But really I was confused.
In my code, I want to know if saving a model is successful or not.
$model = Model::find(1);
$model->attr = $someVale;
$saveStatus = $model->save()
So, I think $saveStatus must show me if the saving is successful or not, But, now, the model is saved in the database while the $saveStatus value is NULL.
I am using Laravel 7;
save() will return a boolean, saved or not saved. So you can either do:
$model = new Model();
$model->attr = $value;
$saved = $model->save();
if(!$saved){
//Do something
}
Or directly save in the if:
if(!$model->save()){
//Do something
}
Please read those documentation from Laravel api section.
https://laravel.com/api/5.8/Illuminate/Database/Eloquent/Model.html#method_getChanges
From here you can get many option to know current object was modified or not.
Also you can check this,
Laravel Eloquent update just if changes have been made
For Create object,
those option can helpful,
You can check the public attribute $exists on your model
if ($model->exists) {
// Model exists in the database
}
You can check for the models id (since that's only available after the record is saved and the newly created id is returned)
if(!$model->id){
App::abort(500, 'Some Error');
}
Where and how I am overriding the save method in Joomla 3.0 custom component ?
Current situation:
Custom administrator component.
I have a list view that displays all people stored in table.
Clicking on one entry I get to the detailed view where a form is loaded and it's fields can be edited.
On save, the values are stored in the database. This all works fine.However, ....
When hitting save I wish to modify a field before storing it into the database. How do I override the save function and where? I have been searching this forum and googled quiet a bit to find ways to implement this. Anyone who give me a simple example or point me into the right direction ?
Thanks.
Just adding this for anyone who wants to know the answer to the question itself - this works if you explicitly wish to override the save function. However, look at the actual solution of how to manipulate values!
You override it in the controller, like this:
/**
* save a record (and redirect to main page)
* #return void
*/
function save()
{
$model = $this->getModel('hello');
if ($model->store()) {
$msg = JText::_( 'Greeting Saved!' );
} else {
$msg = JText::_( 'Error Saving Greeting' );
}
// Check the table in so it can be edited.... we are done with it anyway
$link = 'index.php?option=com_hello';
$this->setRedirect($link, $msg);
}
More details here: Joomla Docs - Adding Backend Actions
The prepareTable in the model (as mentioned above) is intended for that (prepare and sanitise the table prior to saving). In case you want to us the ID, though, you should consider using the postSaveHook in the controller:
protected function postSaveHook($model, $validData) {
$item = $model->getItem();
$itemid = $item->get('id');
}
The postSaveHook is called after save is done, thus allowing for newly inserted ID's to be used.
You can use the prepareTable function in the model file (administrator/components/yourComponent/models/yourComponent.php)
protected function prepareTable($table)
{
$table->fieldname = newvalue;
}
I am trying to add a new field (subscriber_type) to the newsletter subscribe form. I have setup my observer and it is working and firing correctly (newsletter_subscriber_save_before):
<?php
class Mynamespace_Enhancednewsletter_Model_Observer {
public function saveBefore($observer){
$subscriber = $observer->getEvent()->getSubscriber();
$type = Mage::app()->getRequest()->getParam('type'); // this contains my new data correctly
$subscriber->setSubscriberType($type);
return $this;
}
}
I have also added the field to the db.
The above code adds the new subscriber but doesn't add the subscriber_type.
Can anyone see where I'm going wrong?
Thanks
Man this one was frustrating..but the answer was so simple:
Magento caches table descriptions so make sure you clear your cache after adding a new field to the db.
Thanks to MJA for the answer:
https://stackoverflow.com/a/10550476/491055
I'm having a heck of a time figuring out the code/parameters to hole-punch the Full Page Cache in magento for the Mage_Catalog_Block_Product_Price block. I can get the price to show the first time the page is loaded, but when the cache id is unique, it's not rendering the price properly (it does cache it correctly when it's supposed to be cached) . I know I need to send it parameters, such as product_id etc, but not clear about what (eg 'xx') needs to be sent from getCacheKeyInfo into the cache container for use in $this->_placeholder->getAttribute('xx'). And what needs to be prepared and sent from _renderView() to the price layout/view.
So far I have done the following successfully (they each output testing data)
Created the cache.xml in my module /etc folder
Created the cache container model and verified works (just need settings)
Rewrote/extended the Mage_Catalog_Block_Product_Price into my own model to add the getCacheKeyInfo()
So the problem is that I have tried many variations within the container model's _getCacheId() and _renderBlock() in combination with the getCacheKeyInfo(), like described above. But I am hitting a stumbling block. If anyone can lead me in the right direction, it would be greatly appreciated.
I've been struggling with the Full Page Caching as well.
These are my findings and have been very helpful to me.
Please take a look at: app/code/core/Enterprise/PageCache/Model/Processor/Default.php Line 47
/**
* Check if request can be cached
*
* #param Zend_Controller_Request_Http $request
* #return bool
*/
public function allowCache(Zend_Controller_Request_Http $request)
{
foreach ($this->_noCacheGetParams as $param) {
if (!is_null($request->getParam($param, null))) {
return false;
}
}
if (Mage::getSingleton('core/session')->getNoCacheFlag()) {
return false;
}
return true;
}
Looking at this function there seem to be two ways of avoiding (disabling) the Full Page Cache:
GET Parameter:
You can use the parameters 'store' or 'from_store' prefixed with three underscores to avoid the cache.
Example:
http://magentourl.com/catelog/category/view/id/123?___store
Mage::getUrl('catalog/category/view', array('id' => 123, 'query' => array('___store' => '')))
Session variable:
You could also avoid the Full Page caching by setting a (temporary) session variable:
Mage::getSingleton('core/session')->setNoCacheFlag(true)
isn't this the right method to get Name of logged in customer?
<?php echo Mage::helper('customer')->getCustomer()->getName(); ?>
I have a website with live chat functionality. Yesterday I have been asked to pass email address and the name of the logged into the user into the Javascript Tracking variable code placed in the head section of the website. So that the operators could see who is on the website and whom are they talking to without any need to ask about their information.
So I passed the information from Magento into the Javascript code but now I see this very strange thing happening. For example,
If I am logged in with credentials Name = John Email =
john12#yahoo.com
Then This name and email variable values are changing with the change of pages. For example if I click on any product page the variable values which I am passing changes to some other user's information.
Name becomes Ricky Email becomes ricky23#gmail.com
this variable values are kept on changing back to john and from john to something else with the change of pages. So operator does not have any idea whom are they talking because the values are kept on changing. Also, user ricky or who ever it changes to also exist in the database. so it is picking up random person from the database.
This is what i did to pass the code to javascript. Please let me know if that is not the right code to pass the information. Please check the php code I am using to fetch information from Magento. Roughly, I receive incorrect value once in 5 times. Please provide some assistance. Thanks in advance.
<?php
$customer = Mage::getSingleton('customer/session')->getCustomer();
$email = $customer->getEmail();
$firstname = $customer->getFirstname();
$lastname= $customer->getLastname();
$name = $firstname . ' ' . $lastname;
?>
<script type="text/javascript">
if (typeof(lpMTagConfig) == "undefined"){ lpMTagConfig = {};}
if (typeof(lpMTagConfig.visitorVar) == "undefined"){ lpMTagConfig.visitorVar = [];}
lpMTagConfig.visitorVar[lpMTagConfig.visitorVar.length] = 'Email=<?php echo $email; ?>';
lpMTagConfig.visitorVar[lpMTagConfig.visitorVar.length] = 'Name=<?php echo $name; ?>';
</script>
I'm also attaching a snap shot
I'd be interested to hear how you're adding this code to the page? Is it in it's own block, or are you adding it to footer.phtml, or similar? If your adding to an existing block be sure to check the block caching settings of that template.
To confirm the caching hypothesis I'd ask the following:
Do you get the same name, all the time, on the same page? When you refresh the page, do you get the same name and email in the Javascript?
Does the problem persist with caching disabled?
This doesn't sound like a singleton problem at all. Each execution of the PHP script is isolated from the others, serving one page request. There's no chance of another customer's object moving between invokations of the script.
It is a matter of understanding the singleton pattern. If you call your code twice:
$customer_1 = Mage::helper('customer')->getCustomer()->getName();
$customer_2 = Mage::helper('customer')->getCustomer()->getName();
you get two different instances of the object. But... if one of them has already implemented a singleton pattern in its constructor or has implemented a singleton getInstance then both objects will actually point to the same thing.
Looking at the customer/helper/Data.php code you can see the function
public function getCustomer()
{
if (empty($this->_customer)) {
$this->_customer = Mage::getSingleton('customer/session')->getCustomer();
}
return $this->_customer;
}
That means that in one of the cases singleton is already implemented/called and in other one - not as the property is already set.
The correct way to work with quote/customer/cart in order to get always the correct data is always to use the singleton pattern.
So using this:
$customer = Mage::getSingleton('customer/session')->getCustomer();
always guarantee that you get the correct customer in that session. And as may be you know singleton pattern is based on registry pattern in app/Mage.php:
public static function getSingleton($modelClass='', array $arguments=array())
{
$registryKey = '_singleton/'.$modelClass;
if (!self::registry($registryKey)) {
self::register($registryKey, self::getModel($modelClass, $arguments));
}
return self::registry($registryKey);
}
and looking at app/Mage.php:
public static function register($key, $value, $graceful = false)
{
if (isset(self::$_registry[$key])) {
if ($graceful) {
return;
}
self::throwException('Mage registry key "'.$key.'" already exists');
}
self::$_registry[$key] = $value;
}
...
public static function registry($key)
{
if (isset(self::$_registry[$key])) {
return self::$_registry[$key];
}
return null;
}
you can see that Magento checks is it is already set. If so, Magento will either throw an Exception, which is the default behavior or return null.
Hope this will help you to understand the issue you face.
I have sorted this out. I have moved the code from footer.phtml to head.phtml and it's working fine now.Values are not changing anymore. If anyone know the logic behind please post and I will change my answer. So far this is working.