Magento returning incorrect customer data on frontend pages - magento

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.

Related

CodeIgniter hide post id and only slug URL

I'm working on custom blog based on CodeIgniter. Got some problems at the moment I've achieved url:
/blog/view/1/my-very-first-post
I'm not happy with that I'd like to get rid off id and "/view"
That's how my controller looks like:
function index($postId=null)
{
$this->view($postId=null);
}
function view($postId, $str_slug = '')
{
$data['title'] = ucfirst("Blog");
$data['post'] = $this->posts->get_posts($postId);
if($postId !== null)
{
$this->load->view('templates/head', $data);
$this->load->view('templates/header', $data);
$this->load->view('posts/single_view', $data);
$this->load->view('templates/footer',$data);
} else {
$this->load->view('templates/head', $data);
$this->load->view('templates/header', $data);
$this->load->view('posts/index', $data);
$this->load->view('templates/footer',$data);
}
$row = $this->db->get_where('posts', array('id' => $postId))->row();
if ($row and ! $str_slug) {
$str_slug = url_title($row->title, 'dash', TRUE);
redirect("blog/view/{$postId}/{$str_slug}");
}
}
What is the best way to achieve this?
Thanks!!
Adam
I think you're looking for the _remap() method. You can read more about it here: http://ellislab.com/codeigniter/user-guide/general/controllers.html#remapping
Your code would look something like below. You still need to implement the get_posts_by_slug() method if you still need it.
public function _remap($slug) {
$data['title'] = ucfirst("Blog");
$data['post'] = $this->posts->get_posts_by_slug($slug);
if($slug !== null)
{
$this->load->view('templates/head', $data);
$this->load->view('templates/header', $data);
$this->load->view('posts/single_view', $data);
$this->load->view('templates/footer',$data);
} else {
$this->load->view('templates/head', $data);
$this->load->view('templates/header', $data);
$this->load->view('posts/index', $data);
$this->load->view('templates/footer',$data);
}
$row = $this->db->get_where('posts', array('slug' => $slug))->row();
}
Update:
Hey #AdamLesniak - it's generally good design to store a permalink to a blog post or a news article, so that it's not dependent on the title or any other volatile data structure in order to still be accessible.
But for a different approach, personally, I really think this is a nice system:
http://localhost/blog/my-news-article-title-permalink/3
The main issue is that if you don't store the slug/permalink somewhere, then you're going to feel sad when somebody changes the title of an article. Example, my article called "Hello World First Blog Post", which is accessible at:
http://localhost/blog/hello-world-first-blog-post
Changes into "First post I ever made":
http://localhost/blog/first-post-i-ever-made
So what happens to the initial URL? It's no longer accessible - any user that comes on the website via a search engine, or through somebody's link will now no longer see your comment and will instead get a 404 page, which you want to avoid.
A problem with using permalinks on their own is that you need to make sure they're unique, and extra constraints need to be set in place for that.
There are a few tricks that you can do, but they all have their pitfalls. You can for instance use the system I've mentioned above, where you stick the unique identifier at the end of the URL:
http://localhost/blog/hello-world/3
And if the title changes, you don't really care, because you're not using the slug to make your searches, but instead, you're relying on the unique identifier.
http://localhost/blog/first-post-i-ever-made/3
However I've seen opinions that this sort of system is against the idea of an URL (Uniform Resource Locator). I've used it in back when I was starting out, and it proved to be a flexible system; it's definitely nice to experiment with at least.
BBC do a variant of the above, by keeping the category that an article belongs to and the unique identifier for the entry:
http://www.bbc.co.uk/news/business-24511283
Basically, they know that an article will never change its category, although it may change its title, so they just keep the general topic, which is business and the unique identifier 24511283.
In the end, what I suggest you do, as it's by far the most scalable solution is to just generate the following format:
http://localhost/blog/permalink/unique-id
The format above lets you have unique identifiers, which are important for guaranteeing singularity, and permalinks for all the search engine friendly-ness! Now if the title of the article changes, display the updated title to the user on the page, but don't do anything to the permalink, so that your URLs never change.
By also using IDs in the URL, you know for sure that you can use a permalink multiple times, and your system will still scale correctly.
I wrote a tutorial on this which may or may not help: http://www.rappasoft.com/tutorials/14-seo-friendly-links-with-codeigniter.html

How to override save() method in a component

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

CodeIgniter - Dynamic URL segments

I was wondering if someone could help me out.
Im building a forum into my codeigniter application and im having a little trouble figuring out how i build the segments.
As per the CI userguide the uri is built as follows
www.application.com/CLASS/METHOD/ARGUMENTS
This is fine except i need to structure that part a bit different.
In my forum i have categories and posts, so to view a category the following url is used
www.application.com/forums
This is fine as its the class name, but i want to have the next segment dynamic, for instance if i have a category called 'mycategory' and a post by the name of 'this-is-my-first-post', then the structure SHOULD be
www.application.com/forums/mycategory/this-is-my-first-post
I cant seem to achieve that because as per the documentation the 'mycategory' needs to be a method, even if i was to do something like /forums/category/mycategory/this-is-my-first-post it still gets confusing.
If anyone has ever done something like this before, could they shed a little light on it for me please, im quite stuck on this.
Cheers,
Nothing is confusing in the document but you are a little bit confused. Let me give you some suggestions.
You create a view where you create hyperlinks to be clicked and in the hyperlink you provide this instruction
First Post
In the controller you can easily get this
$category = $this->uri->segment(3);
$post = $this->uri->segment(4);
And now you can proceed.
If you think your requirements are something else you can use a hack i have created a method for this which dynamically assign segments.
Go to system/core/uri.php and add this method
function assing_segment($n,$num)
{
$this->segments[$n] = $num;
return $this->segments[$n];
}
How to use
$this->uri->assign_segment(3,'mycategory');
$this->uri->assign_segment(4,'this-is-my-first-post');
And if you have error 'The uri you submitted has disallowed characters' then go to application/config/config.php and add - to this
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
You could make a route that forwards to a lookup function.
For example in your routes.php add a line something like;
$route['product/(:any)/(:any)'] = "forums/cat_lookup/$1/$2";
This function would then do a database lookup to find the category.
...
public function cat_lookup($cat, $post) {
$catid = $this->forum_model->get_by_name($cat);
if ($catid == FALSE) {
redirect('/home');
}
$post_id = $this->post_model->get_by_name($post);
/* whatever else you want */
// then call the function you want or load the view
$this->load->view('show_post');
}
...
This method will keep the url looking as you want and handle any problems if the category does not exist.Don't forget you can store the category/posts in your database using underscores and use the uri_title() function to make them pretty,
Set in within config/routes.php
$route['song-album/(:any)/:num'] = 'Home/song_album/$id';
fetch in function with help of uri segment.
$this->uri->segment(1);

Customer session is different in different parts of a Magento website

I have a function inside of a Helper in Magento that returns whether or not a customer attribute equals one.
Here is my Helper class
class Nie_Nie_Helper_Data extends Mage_Core_Helper_Abstract {
public function isNieAdmin() {
if(Mage::getSingleton('customer/session')->getCustomer()->getNieAdmin() == 1) {
return true;
} else {
return false;
}
}
}
Now when I call this function from a class that extends Mage_Core_Block_Template, everything seems to work fine. However when I try to use this inside one of my controllers, it does not work. In fact when I do Mage::getSingleton('customer/session')->getCustomer()->debug() the only variable that is returned is the website_id.
Does anyone know what I have to do in order to get this to work?
At the time of the controller the session objects are not yet initialised (although the session variable must be) so it returns a blank model. My guess is the website_id is deliberately set in the creation of a customer object to act as a default.
You could access $_SESSION['customer'] directly to find what you need, but that is messy. An alternative would be to do what you want in an event that occurs later.
I hope someone can come up with a better answer than mine.
Ok it looks like I had to load up the session myself. I had to put the following in my functions:
Mage::getSingleton('core/session', array('name' => 'frontend'));
Hope this helps.

Magento createBlock method not working, displaying static block data

Ok so Ive created static blocks in my CMS area, and Im trying to output them inside of a custom homepage template Ive built.
Every document I can find says to output the block as follows
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('my-block-identifier')->toHtml() ?>
That didnt work for me, so then I tried another way. --
<?php $block = Mage::getSingleton('core/layout')->createBlock('cms/block')->setBlockId('my-block-identifier');
echo $block->toHtml();
All the sites referencing this tell me to use the actual blocks identifier to get the block. So then I decide to manually lookup the block_id in my cms_block table and see if using the block_id number in place of the literal my-block-identifier name will work - and it did. So I am confused... Can anyone tell me how I can get the block by the actual identifier, or look up the blocks id by the identifier so that I can grab the block by block name?
Any help much appreciated.
Looking at the cms/block block source, those tutorials have mislead you, or you misinterpreted them.
#File: app/code/core/Mage/Cms/Block/Block.php
class Mage_Cms_Block_Block extends Mage_Core_Block_Abstract
{
protected function _toHtml()
{
if (!$this->_beforeToHtml()) {
return '';
}
$html = '';
if ($blockId = $this->getBlockId()) {
$block = Mage::getModel('cms/block')
->setStoreId(Mage::app()->getStore()->getId())
->load($blockId);
if (!$block->getIsActive()) {
$html = '';
} else {
$content = $block->getContent();
$processor = Mage::getModel('core/email_template_filter');
$html = $processor->filter($content);
}
}
return $html;
}
}
The block content is always loaded with ->load($blockId); -- load with one parameter always means loding by a database ID.
So, with no supported way of doing this built into the block, you'll need to look up the block ID.
$model = Mage::getModel('cms/block')->getCollection()
->addFieldToFilter('identifier','footer_links')
->getFirstItem();
var_dump($model->getBlockId());
In the admin, when you are editing the contents of the static block, you will see a field called Identifier second from the top. Copy the value of that field, and insert it into your code. So if your Block is called contact-info in the admin, then your code will look like:
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('contact-info')->toHtml() ?>
The value in that Identifier textbox in the admin is also what will be saved into the cms_block table, as you're worked out.
HTH,
JD

Resources