Passing an array from Codeigniter to Smarty - codeigniter

I'm using Codeigniter with Smarty as my template engine. I have a main template
(master.tpl) that I am inheriting in my page templates. In one of my pages I'm trying to access data that was pulled from the database, but I have not been successful yet.
My model looks like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class company extends CI_Model
{
public function __construct()
{
// Call the constructor
parent::__construct();
// Load database access
$this->load->database();
}
public function get_companies()
{
// Query the companies table
$query = $this->db->get('companies');
return $query->result();
}
}
My controller looks like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Companies extends CI_Controller {
public function index()
{
// Load the companies model
$this->load->model('company');
$companies = $this->company->get_companies();
$data['complist'] = $companies;
//load the department_view
$this->load->view('companies',$data);
}
}
and this is the main part of my page view:
...
<tbody>
{foreach from=$companies item=company}
<li>{$data.name}</li>
{/foreach}
</tbody>
...
The code block in my master.tpl that is inherited in the page view looks like this:
...
{block name=content}{/block}
...
I'm simply trying to display a list of companies retrieved from my database but I can't figure out how to access the array that holds the data. What am I doing wrong?
EDIT:
Here are a the error messages I get:
Message: Undefined index: companies
Message: Trying to get property of non-object

Try making companies like so $data['companies'] = $this->company->get_companies();
And autoload your database library in config/autoload.php much better.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Companies extends CI_Controller {
public function index() {
$this->load->model('company');
$data['companies'] = $this->company->get_companies();
$this->load->view('companies',$data);
}
}
Model
Make Model Class change company to Company
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Company extends CI_Model {
public function __construct() {
parent::__construct();
}
public function get_companies() {
$query = $this->db->get('companies');
if ($query->num_rows() > 0) {
return $query->result();
// or
// return $query->result_array();
} else {
return false;
}
}
On view I know you use smarty but php way Example normal php on view with out smarty just example.
<?php foreach ($companies as $company) {?>
<?php echo $company['name'];?>
<?php }?>
Smarty
<tbody>
{foreach from = $companies item = $company}
<tr>
<td>{$company.name}</td>
</tr>
{/foreach}
</tbody>

As Tpojka mentioned, I was trying to access the wrong variable so I had to change that, but the syntax in the foreach loop was $companies->name. This is what the loop in the template now looks like:
{foreach from=$companies item=company}
<tr>
<td>{$company->name}</td>
<td>{$company->address}</td>
<td>{$company->city}</td>
<td>{$company->phone}<td>
<td>{$company->email_address}</td>
<td class="center">
<a class="btn btn-success" href="#">
<i class="fa fa-search-plus "></i>
</a>
<a class="btn btn-info" href="#">
<i class="fa fa-edit "></i>
</a>
<a class="btn btn-danger" href="#">
<i class="fa fa-trash-o "></i>
</a>
</td>
</tr>
{foreachelse}
No records found.
{/foreach}

Related

Fetching post comment order by in laravel

I want to fetch comment order by created at but how can i do that?
I did it as usual order by but it didnot work.
#foreach( $post->comnt->take(1)->orderBy('created_at','DESC') as $comments )
#if($post->comnt)
<div class="comments clearfix">
#foreach( $post->comnt->take(1) as $comments )
<div class="each_coments clearfix">
<p> <span class="comment_profile"><img src="{{ asset('img').'/'.$comments->user->image }}" alt=""></span></p>
<p>{{ $comments->user->username }}{{ $comments->comment }}</p>
</div><?php $last_id = $comments->id ?>
#endforeach
<a data-lastid="#if(!empty($last_id)){{$last_id}}#else{{'0'}}#endif" href="">lode more comments</a>
</div>
<?php unset($last_id); ?>
#endif
Here is my post model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table = 'posts';
public function user()
{
return $this->belongsTo('App\User');
}
public function likes()
{
return $this->hasMany('App\like');
}
public function comnt()
{
return $this->hasMany('App\comment');
}
}
Maybe
public function comnt()
{
return $this->hasMany('App\comment')->orderBy('created_at','DESC');
}

Undefined Variable: rows and How to display image slider in Codeigniter 3

Please help me for this...I am learning CodeIgniter 3 and i got stuck on this error.
I am getting an error:
Notice: Undefined variable: slid and Invalid argument supplied for foreach(). Can anyone give me suggest to resolve this?
Controller : home.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
function __construct()
{
parent::__construct();
}
function sliders(){
$slider = $this->slider_model->get_slider();
if ($slider){
$data['slid'] = $slider;
}
$this->template->display('home',$data);
}
}
Model : slider_model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Slider_model extends CI_Model {
function __construct()
{
parent::__construct();
}
function get_slider()
{
$r = $this->db->get('slider');
$data = $r->result();
return $data;
}
}
View : home.php
<div id="slider" class="fixed">
<div class="background-slider"></div>
<div class="background">
<div class="shadow"></div>
<div class="pattern">
<div class="container" id="camera_1">
<div class="camera_slider">
<div class="spinner"></div>
<div class="camera_wrap" id="camera_wrap_1" style="height: 465px">
<?php foreach($slid as $r){ ?>
<div><img src="<?php echo base_url();?><?php echo $r->image?> " alt="Slider">
</div>
<?php } ?>
</div>
</div>
</div>
</div>
</div>
</div>
This is script of Js
< script type = "text/javascript" >
var camera_slider = $("#camera_wrap_1");
camera_slider.owlCarousel({
slideSpeed: 300,
lazyLoad: true,
singleItem: true,
autoPlay: 7000,
stopOnHover: true,
navigation: true
});
$(window).load(function() {
$("#camera_1 .spinner").fadeOut(200);
$("#camera_wrap_1").css("height", "auto");
}); < /script>
Please try in this code
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('slider_model');
}
function sliders(){
$slider = $this->slider_model->get_slider();
if ($slider){
$data['slid'] = $slider;
}
$this->template->display('home',$data);
}
}

Codeigniter - Call to undefined function set_value()

im new on codeigniter and try to resolve following problem for hours now.
I try to set_value in a form but when i set it i get following error:
A PHP Error was encountered
Severity: Error
Message: Call to undefined function set_value()
Filename: modals/register_modal.php
Line Number: 27
Backtrace:
When i delete set_value() on line 27, everything works fine.
Line number 27 is the set_value() line:
<div class="row">
<div class="form-group">
<label class="control-label sr-only">Vorname:</label>
<div class="col-md-8 col-md-offset-2 col-xs-10 col-xs-offset-1">
<input type="text" class="form-control" name="firstname" placeholder="Vorname" value="<?php echo set_value('firstname'); ?>" size="50" />
<i class="fa form-control-feedback" aria-hidden="true"></i>
</div>
</div>
</div>
Thats my controller:
class Form extends CI_Controller {
public function index()
{
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('firstname', 'Vorname', 'required|callback_username_check');
$this->form_validation->set_rules('surename', 'Nachname', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Passwort', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('modals/register_modal');
}
else
{
$this->load->view('modals/login_modal');
}
}
public function username_check($str)
{
if ($str == 'test')
{
$this->form_validation->set_message('username_check', 'The {field} field can not be the word "test"');
return FALSE;
}
else
{
return TRUE;
}
}
}
I also set Auto-Load:
$autoload['helper'] = array('form');
You must load library('form_validation') in your Controller.
This work for me:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller{
public function __construct(){
parent::__construct();
$this -> load -> library('form_validation');
}
....
In CodeIgniter4 you have only to use the helper function to load the library
<?php namespace App\Controllers;
use App\Models\UserModel;
class Users extends BaseController {
public function index()
{
helper (['form']);
......
Add helper HTML
protected $helpers = ['form','url','html'];
It worked for me
You can add form helper in BaseController.php. you don't need to add in every cotnroller - codeigniter 4
Edit in BaseController.php
protected $helpers = ['form'];
helper(['form']);
Load the form helper in your function

How I display title in categories only one title in one blogpost?

Hi all i'm a new of codigniter I create post and join two table I want to show categories title only one in my blog post .but it not folow me.it show many title categories in every post.
My Code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Site extends CI_Controller {
function index(){
$this->home();
}
function home(){
$this->load->view('header_view');
$this->load->view('slide_view');
$this->load->view('crumb_view');
$this->load->view('footer_view');
}
function menu(){
$this->load->model('tinjeat_md');
$data["menu_pro"] = $this->tinjeat_md->menu_get();
$this->load->view('header_view');
$this->load->view('crumb_view');
$this->load->view('menu_view',$data);
$this->load->view('footer_view');
}
}
<?php
class Tinjeat_md extends CI_Model{
function __construct(){
parent::__construct();
}
function menu_get(){
$this->db->select('*');
$this->db->from('menu','categories_menu');
$this->db->join('categories_menu','menu.cate_id=
categories_menu.id','left');
$query = $this->db->get();
return $query->result();
}
}
?>
View:
<div class="menu">
<?php foreach ($menu_pro as $value): ?>
<p class="title_cate">
<?php echo $value->cate_name_menu; ?>
</p>
<div class="menu_image">
<?php
echo img(array(
'src'=>'./images/'.$value->image,
'width'=>'220px',
'height'=>'150px'
));
?>
</div>
<div class="menu_description">
<h3><?php echo $value->title; ?></h3>
<p><?php echo $value->description; ?></p>
<p>Prices:<?php echo $value->prices; ?></p>
</div>
<?php endforeach; ?>
</div>
My database:
categories_menu
-id
-cate_menu_name
menu
-id_menu
-title
-image
-description
-prices
-cate_id
In your model.Try like this.
function menu_get(){
$this->db->select('*');
$this->db->from('menu');
$this->db-join('categories_menu','menu.cate_id=categories_menu.id','left');
$query = $this->db->get();
return $query->result();
}
for user guide
you can check your sql query by using $this->db->last_query().

How to use ajax with codeigniter's modules

I have a page written in codeigniter framework.
Now I want to add a button to page (eg 'show more') that will get data with 'ajax.php' from the database and display them on the site, but I do not want it separately connect to the database and then get the results, just want to be able to collect data (in ajax.php) as well as in codeigniter controllers (using models)...
Hope you understand me :)
Here you go just add view more button and call this js and ajax function..This is code i have used please see it and use it as per your requirment
$('.more').live("click",function()
{
var this_tag = $(this);
var ID = $(this).attr("id");
if(ID)
{
$("ol#updates").addClass('tiny-loader');
this_tag.html('Loading.....');
$.post(siteUrl+"ajax/ajax_more",{lastmsg:ID,restid:$(this_tag).data("restid")},function(html){
$("ol#updates").removeClass('tiny-loader');
$("ol#updates").append(html);
$("#more"+ID).remove();// removing old view-more button
});
}
else
{
this_tag.fadeOut('slow');// no results
}
return false;
});
code in ajax file
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Ajax_more extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('general_model');
$this->limit =REVIEW_DETAIL;
}
public function index($offset = 0)
{
$lastmsg=$this->input->post('lastmsg');
$rest_id=$this->input->post('restid');
$value=('reviews.*,usermaster.Name as User');
$joins = array
(
array
(
'table' => 'tk_usermaster',
'condition' => 'usermaster.Id = reviews.UserId',
'jointype' => 'leftouter'
),
);
$this->results = $this->general_model->get_joinlist('reviews',$value,$joins,array('reviews.Status'=>'Enable','reviews.RestaurantId'=>$rest_id,'reviews.Id <'=>$lastmsg),'reviews.Id','desc',$this->limit,$offset);
$data['list_review']= $this->results['results'];
?>
<?php foreach ($data['list_review'] as $row): ?>
<div class="user_reviews_data" >
<div class="width-20 float-left">
<span class="padleft-10"><?php echo $row->User; ?> </span>
<br/>
<span class="padleft-10 "><div class="rateit" data-rateit-value="<?php echo $row->Rating;?>" data-rateit-ispreset="true" data-rateit-readonly="true"></div></span>
<div class="muted padleft-10 float-left"><small><?php echo date('dS M Y' ,strtotime($row->CreatedDate)); ?></small></div>
</div>
<div class="width-80 float-left"><?php echo $row->Feedback;?></div>
<span class="report_span">Report this Feedback <img src="<?php echo base_url();?>themes/images/FLAG_GREY.png"></span>
</div>
<?php
$msg_id = $row->Id;
endforeach; ?>
</div>
<div id="more<?php echo #$msg_id; ?>" class="btn-container center_text morebox">
View More
</div>
<?php
}
}

Resources