I am developing my first big application using codeigniter and need a little help as I am fairly new to it all. I know how to get records out of the DB and display them, but I now have to get results from two tables and display them. I pass $data to the view, it works fine for $data['prop'] but I can't get the rest.
$data['prop'] = $this->ManageProperty_model->get_property_details($p_id);
$data['img'] = $this->ManageProperty_model->get_property_images($p_id);
$this->load->model('ManageBranch_model');
$data['branch'] = $this->ManageBranch_model->get_branch_details($p_id);
I usually echo out results like so:
<?php foreach ($prop as $p) : ?>
<?php echo $p->ID; ?>
<?php endforeach; ?>
Even if there is only 1 row being returned as I am not sure of another way.do I need a foreach for img and branch?
How about using a join?
I dont know whats in your model but if you try something like
$this->db->from('property');
$this->db->join('branch', 'branch.id = property.id');
You can put a where statement in there too if you need something particular.
This means you have a more complex model but less loops and arrays and messy stuff in the view which is what you want.
Yes, currently you're just getting one or the other. You're probably better to put it into a multilevel array like $data['property']['prop'].
Related
I have a collection that contains an array with 2 objects in it. I'm trying to get the email attribute, right now there are only 2 objects, but there could be 100 objects, so I'm not sure if I need a loop or if I need to use array_merge, or something.
I've attached a screenshot of the data, I'm not showing the attributes, but just know that one of them is email.
I'm die/dumping a variable called $tokens.
In the end, it should return a list of emails, for example:
john.doe#email.com
jane#email.com
thomas.brown#email.com
And I need this logic in the controller, not in the view (.blade), because I'm trying to save this data in a csv file, using fputcsv, that's the main objective and idea here.
Thank you to #jagcweb for the inspiration, his code/answer just needed a couple of tweaks. The following works and does what I was trying to do:
$emails_array = array();
for($i=0; $i <= sizeof($tokens)-1; $i++) {
array_push($emails_array, $tokens[$i]["email"]);
}
Now the $emails_array contains an array with both emails in it.
This sounds like what pluck is for:
$tokens->pluck('email')
Laravel 8.x Docs - Collections - pluck
When I loop data from database I need value from that to query again. I query database directly from view. I want to know that is my code wrong? If wrong what is the better way?
foreach($data->result() as $row1) {
echo '<li>';
echo $row1->Name;
echo '<ul>';
$this->db->select('Photo');
$this->db->from('tblPhoto');
$this->db->where('User_id', $row1->User_id);
$photo = $this->db->get();
foreach($photo->result() as $row2) {
echo '<li>';
echo $row2->Photo;
echo '</li>';
}
echo '</ul>';
echo '</li>';
}
The way you're doing it will work, but you may want to consider separating your code to make your code more reusable. For example:
<~~~~ controller ~~~~~>
// your_controller.php:
$this->load->model('your_model');
$data = $this->your_model->get_data();
foreach($data as $key => $obj)
{
$data[$key]->photos = $this->your_model->get_photos($obj->User_id);
}
$this->load->view('test', array('my_data' => $data));
<~~~~ model ~~~~~>
// your_model.php
function get_data()
{
return $this->db->get('yourTable')->result();
}
function get_photos($user_id)
{
return $this->db->get_where('tblPhoto', array('User_id' => $user_id))->result();
}
<~~~~ view ~~~~~>
your_view.php
<?php foreach($my_data as $row1): ?>
<li>
<?php echo $row1->Name;?>
<ul>
<?php foreach($row1->photos as $row2): ?>
<li><?php echo $row2->Photo; ?></li>
<?php endforeach; ?>
</ul>
</li>
<?php endforeach; ?>
Ideally view is not right place to do this.
Firstly all data must be processed between controller/model and should be passed to view.
If case you have a scenario where you want to get data from view after rendering, you should make an ajax call from view to controller and then ask controller to get data from model(data layer).
And respond with data from controller to view and reflect html changes in view depending upon the data received if any changes required.
This is how an MVC architecture should be.
#lyhong, your code is programmatically right.
But, using Codeiginter MVC standards is advisable.
The queries should reside in Models.
So that they can become reusable.
Queries written in Views will serve only that view.
Also, if your write queries in View files, following issues should occur:
In case you do not get
$row1->User_id
the errors should be displayed directly on the page.
Also, it will load your view file slowly.
Benefit of sticking to MVC standards is huge extendibility.
The accepted answer is certainly as good as it gets. I would say that it's worth describing /WHY/ we don't make db queries inside the view. Imagine the view as just that - a view, or a way of viewing the data, or a version of viewing the data (it could be presented in many ways, and the version of how it's presented might change over time, such as they way FaceBook looks now vs. 10 years ago).
And an HTML view is only one way it could be presented; the data could be "viewed" as a PDF, a spreadsheet, a JSON package to be consumed by a microservice, etc. etc.. So if you're NOT calling a database for more information, it's a good indication that you've configured your data well, and it's likely it could be used in multiple ways, robustly.
OK, so guess what? Everything I just said is garbage. I hope you didn't believe it. In actuality, modern presentations and customization present their own complexities such that how the view is to be presented depends on what the data is, the resulting query of which is going to make the needed $data payload needed to be much more complex and possibly take unnecessary time for something that doesn't want to be shown. Run that through to it's logical conclusion, and you'll see the limitations of passing every possible scenario through the view data.
What #abhinsit said above about calling the ancillary stuff via AJAX is a valid point, but know that that adds complexity. But if done well it could save time and make things simpler overall. A good example is including the user information (Hello John Smith) by post-rendering with AJAX. Don't feel guilty if you see a valid need to call the database in the view, but try and structure your view (and your entire framework) so that the important things are already set in state.
I’ve been looking all over for an answer to this. I’ve been using Magento for about a week now and Im fixing a bunch of templates that we messed up. Anyway I’m at a spot now that should probably be easy but its not working. I need to access and custom attribute… this code works.
standard attribute
$_product->getName()
but this code wont.. custom attribute of “designer”
$_product->getDesigner()
the original code from the developer had this.. however this code didn’t work either lol
$_helper->productAttribute($_product, $_product->getDesigner(), 'designer');
any help would be great thanks guys!
How do you get $_product? Maybe u need to make a load.
$_product = Mage::getModel("catalog/product")->load($_product->getId());
Magento doesn't load all attributes of an model until you make an load.
Try to log all data in product by doing Mage::log($_product->getData()).
Make sure that $_product is an instance of Mage_Catalog_Model_Product, or set it to one with $_product = Mage::getModel("catalog/product")->load($_product->getId())
In addition to the "magic" getter of $_product->getDesigner() you could use getData() instead:
$_product = Mage::getModel("catalog/product")->load($_product->getId());
$_designer = $_product->getData('designer');
A client wants all products that are sold out to appear at the end of the product listings and I'm struggling to get it to work at the minute, hence the question. It's worth noting that all the categories in the system are set to only use 'Best Value' positioning for their product ordering and that this repositioning must be done automatically.
Currently I've added an observer to the 'sales_convert_quote_item_to_order_item' event which is the point where the cart items are added to the order itself (seemed like a sensible place to target).
The problem I've found is that obviously the qty available for a product is stored on the products inventory record but the products positioning is stored against the category itself (and then indexed).
I don't really want to resort to using SQL so was hoping someone here would be able to offer some sort of suggestion for a method to use.
My Observer method currently looks like this but it doesn't work because the getUsedProducts method isn't available for some reason. Here it is anyway:
$cart = Mage::getModel('checkout/cart')->getQuote();
foreach($cart->getAllItems() as $key=>$item):
print_r(get_class_methods($item));
echo ">>> ".$item->getProductType();
if($item->getProductType()):
$item = $item->load($item->getId());
//print_r(get_class_methods($item));
$_productCollection = Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null,$item);
print_r($_productCollection);
$stockLevel = 0;
foreach($_productCollection as $product):
$childProductData = $product->getData();
$stockLevel+= $childProductData['stock_item']['qty'];
endforeach;
echo "<br />STOCK LEVEL: $stockLevel<br />";
if($stockLevel <= 0):
echo "ZERO";
//return true;
endif;
endif;
echo "<br />";
endforeach;
I recognise that this isn't a great way of doing this and as such would be quite intensive it there were a lot of products in the cart. But as the order isn't created at this point then I can't use that either.
Any pointers or suggestions would be gratefully received.
Thanks.
If I am correctly understood from the Problem:
...A client wants all products that are sold out to appear at the end of the product listings...
If listings = categories then why don't u change rendering logic? Simply extend catalog product list and override get product collection method.
What u need to achieve is that all sold out products are at the end of the list. So you can sort loaded collection of products with one of these functions.
You can also use Bestseller logic for listing the products.With the help of this link http://inchoo.net/ecommerce/magento/bestseller-products-in-magento/ Or http://blog.magikcommerce.com/how-to-display-best-selling-products-on-magento-store-home-page/ you will know how to get the bestseller products and then you need to call this best seller block in product list.Hope this will help you if you are still searching for the solution.
In Codeigniter I want to know the best practice for using the same views with various functions in a controller.
For eg in the index function I have
$locals['somevar'] = "some thing";
$this->load->view('welcome_message', $locals);
in my view I have something a bit like this:
<?php if($somevar):?>
<?=$somevar?>
<?php endif;?>
Attempting to do a Ruby on Rails thing where I can check the existence of Flash/notice before showing it.
However in the test function
(i.e not passing a variable to the view this time)
$this->load->view('welcome_message')
the view seems to need a $somevar value and errors.
My question is this: Do I have to declare (repeat) the variables and set them to something on every function in a controller tnat wants to use that particular view? I am probably missing something obvious and there is probably a better way of approaching this. Thanks for you help in advance.
<?php if (isset($somevar)): ?>
<?php echo $somevar; ?>
<?php endif; ?>