Magento 2/Wordpress/Fishpig related posts - php

I am currently trying to retrieve a list of related posts on the post article page (post single). I have created a new function within /Block/Post/ListPost.php
public function getRelatedPosts()
{
$posts = $this->getPosts();
die($this->getCategoryId());
return $this->_postCollection;
}
However when I try and output getCategoryId, I get nothing. I'm also unsure how I apply a category filter to the post collection.
Can anyone advise here?

I'm not sure where you have got the getCategoryId method from but this is not part of the ListPost block class so will not work. You cannot just invent methods like this.
You should check the block class for what methods are available. An easy way to do that without even loading the file is to add the following PHP to the class:
echo sprintf('<pre>%s</pre>', print_r(get_class_methods($this)));
exit;
You don't specify in what way the posts should be related but I'm guessing you want to get posts from the same category. One option to do this would be to load the primary category of the post and then get a post collection based on this. If you look in the Post class file, you will see the getParentTerm($taxonomy) method.
if ($category = $post->getParentTerm('category')) {
$relatedPosts = $category->getPostCollection();
// Remove the current post from the collection
$relatedPosts->addFieldToFilter('ID', array('neq' => $post->getId()));
}
You should always look at the class file's you're working with. That is the beauty of open source. You can literally see what methods are available for each object and you can even see how they work.

Related

How do I add a custom field to a model in Laravel?

I'm very new to Laravel and php frameworks in general, so sorry if I miss anything basic. I've created a new model called Journey in my application which extends the standard Eloquent model. What I've noticed is that I'm using my Journey model in two different Controllers and I'm duplicating a bit of code because of it.
Essentially, what I'm doing is I'm taking the title of a Journey and I'm formatting it with a custom class to clean the title (convert to lowercase, add hyphens, remove whitespace, etc) so I can append it to my page URLs.
In one controller, I'm calling:
$journey = Journey::find($id);
$journey->cleanURL = Url::clean($journey['name']); // This creates a new element/property with a clean string
And in the other, I'm calling:
$journeys = Journey::all();
foreach ($journeys as $journey) {
$journey->cleanURL = URL::clean($journey['name']);
}
It would be inappropriate to add a fixed field to my database with the cleaned URL because I may change the title (which the cleaned URL is based on) at any time and I'd like the URL to update automatically in this event. However, saying this, I'm repeating myself by calling Url::clean twice.
What I'd like to do is write a method or alter an existing method, so that when I call Journey::all() or Journey::find() or any query-based method, the URL field is already present and filled. I've tried looking through some of the Vendor/Eloquent files, but they just make me confused.
How would I go about doing this?
You can use accessor for this.
Add to your Journey model the following function:
public function getCleanUrlAttribute($value)
{
return Url::clean($this->name);
}
Now you will be able to use:
$journey = Journey::find($id);
echo $journey->clean_url;

Pass parameters from view to model in joomla

In a joomla custom made component there are multiple posts on a page, and every post contains multiple comment, so in view i want to call comments by post id. please suggest a good method to make it working.
You have two options. The first, is to attach the comment id as a URL paramater and retrieve it within the model as needed like so:
$comment_id = JRequest::getApplication()->input->get('comment_id');
If you wish to pass in a parameter when calling the model from the view class, you need to get an instance of the MVC path model instead of using the short cut method. So, instead of using this in the JView class:
$this->items = $this->get('Items');
You would do this instead:
$model = $this->getModel();
$this->items = $model->getItems($comment_id);
Hope this helps.

how to create a method on the fly in ci

I'm writing a control panel for my image site. I have a controller called category which looks like this:
class category extends ci_controller
{
function index(){}// the default and when it called it returns all categories
function edit(){}
function delete(){}
function get_posts($id)//to get all the posts associated with submitted category name
{
}
}
What I need is when I call http://mysite/category/category_name I get all the posts without having to call the get_posts() method having to call it from the url.
I want to do it without using the .haccess file or route.
Is there a way to create a method on the fly in CodeIgniter?
function index(){
$category = $this->uri->segment(2);
if($category)
{
get_posts($category); // you need to get id in there or before.
}
// handle view stuff here
}
The way I read your request is that you want index to handle everything based on whether or not there is a category in a uri segment. You COULD do it that way but really, why would you?
It is illogical to insist on NOT using a normal feature of a framework without explaining exactly why you don't want to. If you have access to this controller, you have access to routes. So why don't you want to use them?
EDIT
$route['category/:any'] = "category/get_posts";
That WOULD send edit and delete to get_posts, but you could also just define those above the category route
$route['category/edit/:num'] = "category/edit";
$route['category/delete/:num'] = "category/delete";
$route['category/:any'] = "category/get_posts";
That would resolve for the edit and delete before the category fetch. Since you only have 2 methods that conflict then this shouldn't really be that much of a concern.
To create method on the fly yii is the best among PHP framework.Quite simple and powerful with Gii & CRUD
http://www.yiiframework.com/doc/guide/1.1/en/quickstart.first-app
But I am a big CI fan not Yii. yii is also cool though.
but Codeigniter has an alternative , web solution.
http://formigniter.org/ here.

Get ID of the last product added to the cart in magento

I am trying to get the ID of the product that was most recently added to a user’s cart. A quick google search revealed this function
Mage::getSingleton('checkout/session')->getLastAddedProductId(true);
which is also used in Mage_Checkout_Block_Cart_Crosssell. When I try calling the function in my own controller however, it returns nothing.
I have tried to instantiate a core session via
Mage::getSingleton('core/session', array('name'=>'frontend'))
however this approach does not seem to work. I also tried to create the Crossell block and making the protected method that wraps around getLastAddedProductId function public however that returns null just like it does when I try calling it on its own.
Is there something I have to call or instantiate in order to use this function? Here’s my source listing for reference.
class Mymodule_Addcartaftermath_ItemaddedController extends Mage_Core_Controller_Front_Action {
public function generatemessageAction() {
$parameters = $this->getRequest()->getParams();
if (isset($parameters['ajax_call'])) {
$latest_item_id = Mage::getSingleton('checkout/session')->getLastAddedProductId(true);
$response = array('response' => $latest_item_id);
echo json_encode($response);
} else {
$this->_redirect('/');
}
}
}
I tried poking through the source code, particularly the checkout/model/session.php file in the core and I cannot seem to find the definition of the function. I also looked at it’s parent’s class definition but could not find it there either.
If this method is not available to me is there another way of retrieving the most recent item added? I know that the items are added sequentially and I could perhaps just get the last item of the list of items from the cart however this would not work in the case where the user adds the same item to the cart essentially increasing the quantity rather than actual item itself (e.g. the user adds a laptop the cart when there already is one)
The call to
Mage::getSingleton('checkout/session')->getLastAddedProductId(true);
Is actually clearing the session variable after it is read. Magento uses magic methods extensively. In this case you are using the __call magic method which in turn uses the getData() method. In Mage_Core_Model_Session_Abstract_Varien you will see that they override the default behaviour of getData() to expect the second parameter to be a boolean (The first parameter to getData is the key name for the value you are looking for). That boolean is a flag telling the session to clear the variable after reading.
You could always listen for the checkout_cart_product_add_after event and add the item to your own variable in the session. That event is actually fired on the line before setLastAddedProductId() is called.
try to grep the variable you are looking for. As they are coming from magic methods then its hard to find the exact function you are after so it's easier to see the places where data gets set than where it is used
grep '>setLastAddedProductId' app/code -rsn
to see where the product id gets set to that session variable
app/code/core/Mage/Checkout/Model/Cart.php:255: $this->getCheckoutSession()->setLastAddedProductId($product->getId());
and then you can ask this variable (if it is set else empty())
Mage::getSingleton('checkout/session')->getLastAddedProductId();
and you can see all the things that are in checkout/session and verify if the data is there.
var_dump(Mage::getSingleton('checkout/session'));
Haven't a clue why it works this way but it works for me in Magento 1.6...
<?php
require_once ( "app/Mage.php" );
umask(0);
Mage::app("default");
Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('checkout/session');
$lastadded = $session->getData("last_added_product_id");
print_r($lastadded);
Apparently you have to instantiate the core/session and then the checkout/session. I've tried it every other way but this is the only way I've found it to work. Perhaps someone can explain why it works this way. Hope this helps you out!

CakePHP: Get model instance by url string

I have a CakePHP website and navigaton links are stored in database. What i want is for some navigation entries to call custom function which will return some additional, dynamic data about the link: I want to add a count of articles for link "Vacancies". I could call a function on a model that would return total count. This link is to be rendered on every page.
So i need to get appropriate models instance, but not for the current request, but the request where url points to.
So basically i have url "/en/vacancies". I can get controller name by:
$urlInfo = Router::parse("/en/vacancies");
$controllerName = $urlInfo['controller'];
What would be the reliable way to do that?
Any other solutions for the problem are welcome.
Assuming you have the method to gather the navigation link data in a Model.
App::import('Controller', $controllerName);
$controller = new $controllerName;
$controller->loadModel('YourModel');
$yourModel = $controller->YourModel;
$yourData = $yourModel->your_method();
There are a variety of other ways to do this. But, without knowing more about where you're actually going to be calling this function I can't really provide anymore suggestions.

Categories