I have a model that returns a list of artist's names from a database along with their ID. I want to loop through these artists in my view and create links to their pages with the following format:
http://www.example.com/the-artist-name/artist-portfolio/ID.html
What is the best way to do this?
Controller
$data['artists'] = $this->artists_model->get_all(); // should return array
$this->load->view('yourview', $data);
View
<?php foreach($artists as $artist): ?>
<a href="http://example.com/<?php echo $artist['name']; ?>/artist-portfolio/<?php echo $artist['id']; ?>.html">
<?php echo $artist['name']; ?>
</a>
<?php endforeach; ?>
Pass the data from the model into the view and loop through it like you normally would.
In your controller:
$view_data['artists'] = $this->artist_model->get_artists();
$this->load->view('view.php', $view_data);
In your view:
foreach ($artists as $artist) {
echo "{$artist['name']}";
}
Related
I am trying to the array variable $popular_data in Codeigniter’s view, it is installed with Modesty script.
I tried to append this variable to the one already passed to view by array_merge, $data + $variable
in Model:
public function get_popular_products(){
$popular_data = $this->db->query(‘SELECT... ’)->result_array();
return $popular_data;
}
in Controller:
$this->load->model("Popularproduct_model");
$popularproducts = $this->Popularproduct_model->get_popular_products();
var_dump($popularproducts) here(in controller) shows the queried popular products on top of view as
array(3) {
[0]=>
array(34) {
["id"]=>
string(1) "3"
["title"]=>
string(13) "Patchouli Oil"
["slug"]=>
string(15) "patchouli-oil-3"
...
other variable passed to view as:
$this->load->view('index', $data);
So how to send the $popularproducts to the view and use the values?
Thanks.
store it in $data
$data['popularproducts'] = $this->Popularproduct_model->get_popular_products();
then make foreach inside your view.
foreach($popularproducts as $data){
echo $data['title'].'<br>'.
$data['slug'];
}
at first your can add the data in $data['popularproducts'] and then pass it into the view.
$data['popularproducts'] = $popularproducts;
$this->load->view('index', $data);
Make an array with each of variables:
$data['variable1'] = $variable1;
$data['variable2'] = $variable2;
$data['variable3'] = $variable3;
$this->load->view('template_name',$data) // add data array here in 2nd parameter
In CodeIgniter, we can send data from Controller to view as an associative array.
The function call $this->load->view() has two parameters:
1) View (template) file (path if its not in the default /application/views folder.
2) The associative data array to be passed.
$data['popularproducts'] = $popularproducts;
$this->load->view('index', $data);
If you pass $data in above scenario, your template index.php has a variable $popularproducts.
$popularproducts in the template/view is same as you passed from Controller.
To Pass multiple values from controller to view you should use an array as below given example
Each variable are as examples, you can convert it as per your requirement
Controller:
$data['variable'] = $variable;//from db or hardcoded
$data['arrayofObject'] = $arrayofObject;//from db or hardcoded
$data['arrayofArray'] = $arrayofArray;//from db or hardcoded
$this->load->view('index',$data) // add data array here in 2nd parameter
View:
i.e:
<div>
<span><?php echo $variable; ?></span>
</div>
<div>
<ul>
<?php if(!empty($arrayofObject)) { ?>
<?php for($arrayofObject as $obj) { ?>
<li><?php echo $obj->key; ?></li>
<?php } ?>
<?php } ?>
</ul>
</div>
<div>
<ul>
<?php if(!empty($arrayofArray)) { ?>
<?php for($arrayofArray as $ary) { ?>
<li><?php echo $ary['key']; ?></li>
<?php } ?>
<?php } ?>
</ul>
</div>
I'm trying to seperate the HTML elements from the PHP code within Zend Framework 2, but I have no clue on how to solve this problem/seperate. Im currently echo'ing those HTML elements, which does the job. But there must be a way to seperate the HTML from PHP, instead of echo'ing the HTML elements.
At the moment I made a viewhelper which helps me to let me generate this treeMap for other modules aswell, since those will also use this feature, aslong as this helper is given with a treeMap. The categoryTreeMap contains a treemap of category (Doctrine 2 ORM) objects.
This is what I've got so far:
namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper;
class CategoryTreeMapHelper extends AbstractHelper
{
public function __invoke($categoryTreeMap)
{
echo "<ol class=\"sortable\">";
foreach ($categoryTreeMap as $category) {
$this->showCategories($category);
}
echo "</ol>";
}
public function showCategories($category)
{
echo "<li><div>" . $category->name . "</div>";
if (isset($category->childs)) {
echo "<ol>";
foreach ($category->childs as $child_category) {
$this->showCategories($child_category);
}
echo "</ol>";
}
echo "</li>";
}
}
Any suggestions on how to solve this, by seperating the HTML from the PHP echo's.
If your helper solely consist of those two methods, you can replicate the functionality in templates by making use of the partial helper
Create a partial for your treemap container
// view/partial-treemap.phtml
<ol class="sortable">
<?php foreach ($this->categoryTreeMap as $category) :
echo $this->partial('partial-category', array('category' => $category));
endforeach; ?>
</ol>
Create a partial for the recursive part (which calls itself recursively for children)
// view/partial-category.phtml
<li>
<div><?php echo $category->name; ?></div>
<?php if (isset($category->childs)) : ?>
<ol>
<?php foreach ($category->childs as $child_category) :
echo $this->partial('partial-category', array('category' => $child_category));
endforeach; ?>
</ol>
<?php endif; ?>
</li>
Then in your controller action view you only need one line
<?php echo $this->partial('partial-treemap', array('categoryTreeMap' => $categoryTreeMap)); ?>
Where should we process mysql queries in CodeIgniter application?
For example in a simple project we do like this :
for controller:
class Blog extends CI_Controller {
function posts(){
$data['query'] = $this->blog_model->index_posts();
$this->load->view('blog_view', $data);
}
}
and in view :
<?php
while ($post = mysql_fetch_object($query)):
?>
<div>
<p><?= $post->body; ?></p>
</div>
<?php endwhile; ?>
But, if we want to do something with body of post before print where should it be done?
For example, I want to write a function that formats the body of post and pass the body to it before doing echo.
Where should it be placed according to CoeIgniter's structure and recommended practices? (best option)
in the controller? (if so , how to use it)
in the view?
write a helper?
other approaches ?
Here's what is recommended:
Controller:
function posts() {
$this->load->model("blog_model");
$data['rows'] = $this->blog_model->index_posts();
$this->load->view("blog_view", $data);
}
Model: (blog_model.php)
function index_posts() {
$this->load->database();
$query = $this->db->get('your_table');
$return = array();
foreach ($query->result_array() as $line) {
$line['body'] = ... do something with the body....
$return[] = $line;
}
return $return;
}
View: (blog_view.php)
<?php foreach ($rows as $line): ?>
<div>
<p><?php echo $line['column']; ?></p>
</div>
<?php endforeach; ?>
Basically what happens is your model returns a multidimensional array that is passed the view and processed using a foreach() loop.
Good luck!
If you want to reuse that function create a helper. If you want this function only once put it in your controller and call from that controller.
Models are just for accessing database or maybe in few other cases, but mostly just for accessing things in database or editing, deleting etc. and sending the result to controller for further processing.
In your case I would stick with helper.
E.g. you will create a file top_mega_best_functions.php and put it inside helpers folder.
Than you write ther e.g. something like
function red_text($input) {
echo '<span style="color: red;">';
echo $input;
echo '</span>';
}
Then load the helper in your autoloader file or load before using.
And use in your view or controller like
$blablabla = "This text will be red";
red_text($blablabla);
The following link is used in a list of Favours! It links to a place where the user is from but is being used inside the favour list Hence the favour variable.
I have three models Users, Places and Favours. A user has many favours and one place, a favour belongs to a user.
<?php foreach($favours as $favour): ?>
<p><?php echo $this->Html->link($favour['User']['firstname'] . ' ' . $favour['User']['lastname'], array('controller'=>'users','action'=>'view','userName'=>$favour['User']['username'])); ?> in <?php echo $this->Html->link($favour['Place']['name'], array('controller'=>'places','action'=>'view',$favour['Place']['id'])); ?> asked a favour <?php echo $favour['Favour']['datetime']; ?></p>
<h3><?php echo $this->Html->link($favour['Favour']['title'], array('controller'=>'favours','action'=>'view',$favour['Favour']['id'])); ?></h3>
How do I display the link as at the moment I get an error saying that Place is undefined.
This is the controller action for that list:
function index()
{
$favours = $this->paginate();
if (isset($this->params['requested']))
{
return $favours;
}
else
{
$this->set('favours', $favours);
}
}
Make sure you contain Place when fetching data for Favour.
This is how it should look like in your favours_controller:
function index(){
$favours = $this->Favour->find('all');
$places = $this->Favour->Place->find('all');
$this->paginate();
$this->set(compact('users', 'places');
}
This is how it should look like in your index.ctp:
<?php foreach($favours as $favour): ?>
<?php echo $this->Html->link($favour['Favour']['username'], array('controller'=>'users','action'=>'view', $favour['Favour']['username'])); ?>
<?php endforeach; ?>
<?php foreach($places as $place): ?>
<?php echo $this->Html->link($place['Place']['place'], array('controller'=>'places','action'=>'view', $place['Place']['place'])); ?>
<?php endforeach; ?>
You may also need to define the uses variable:
var $uses = array('Place');
My View :-
<html>
<?= link_tag(base_url().'css/simple.css'); ?>
<body>
<?php $this->load->helper('form'); ?>
<?php $this->load->view('commentform'); ?>
<?php $id=$this->uri->segment(3);?>
<?php echo $id;?>
</body>
</html>
i would like to use the variable $id in my controller.I'm using codeigniter by the way, and am a beginner. I would appreciate any help on this.
you should not call the $id from the View, you should get it at the controller level and pass it to the View.
as Bulk said. you URL will be something like that
www.mysite.com/thecontrollername/thefunction/id
for example your controller if home and there is a show_id function in it and your view is call show_id_view.php.
you will have your url like this: www.mysite.com/home/show_id/id
your function in home will read the id"
in your home controller:
function show_id(){
$id=$this->uri->segment(3);
$view_data['id'] = $id;
$this->load->view('show_id_view',$view_data);
}
in the view (show_id_view):
<?php echo $id ?>
nothing else..
hope this helps.
Well, ideally you wouldn't do it this way. You should assign the variable first in the controller and pass it to the view if you need to use it there.
$data['id'] = $this->uri->segment(3);
$this->load->view('view_file', $data);
$id would then be available in your view as well.
in my view i add link
<li><a href="<?php echo base_url()?>link/show_id/mantap"> coba </li>
in my link.php controler i add function show_id
function show_id(){
$id=$this->uri->segment(3);
$data['coba'] = $id;
$this->mobile->view('**daftarmember_form**',$data);
in my next view daftarmember_form.html
)
<?php echo $id;?>
they print mantap,