undefined variable in codeigniter view which is already defined in the controller - codeigniter

This is my controller. here i declared current_company.
public function index($id='')
{
$this->load->model('Company_model');
($id!='') ? $data["company_details"]=$this->Company_model->get_company($id) :'';
($id!='') ? $data ["current_company"]=$this->Company_model->get_currentcomp($id) :'';
$this->load->view('includes/header');
$this->load->view('includes/left_menu');
$this->load->view('company/manage',($id!='') ? $data : '');
$this->load->view('includes/footer');
}
This is my model. Here i declared the function
class Company_model extends CI_Model{
protected $strTableName = 'suc_company';
function __construct(){
parent::__construct ();
$this->db->from($this->strTableName);
}
function get_currentcomp($intPkId){
$this->db->where('pk_bint_company_id',$intPkId);
$q1 = $this->db->get($this->strTableName);
return $q1->result_array()[0];
}
This is the view part. here i called the $current_company !== FALSE then
<div class="form-group">
<label for="company_package" class="col-sm-3 control-label"> Package</label>
<div class="col-sm-9 col-xs-12">
<?php if ($current_company !== FALSE ) {?>
<select name="company_package" class="form-control select2" disabled="">
<option value="<?php echo $company_package;?>" selected=""><?php echo $packagename;?></option>
</select>
<?php } else { ?>
<?php } ?>
Error
an error is occurring... undefined data current_company

Change your controller code like this.
public function index($id='')
{
$this->load->model('Company_model');
$data["company_details"] = false;
$data["current_company"] = false;
if($id != ''){
$data["company_details"] = $this->Company_model->get_company($id);
$data["current_company"] = $this->Company_model->get_currentcomp($id);
}
$this->load->view('includes/header');
$this->load->view('includes/left_menu');
$this->load->view('company/manage',$data);
$this->load->view('includes/footer');
}

As said in comment, you are leaving possibility that maybe $data wouldn't be passed to view file. You have to restrict this kind of oscillations.
Try this way:
public function index($id='')
{
if ((int)$id < 1) {
redirect('some/generic/place', 'refresh');
}
// we have integer in parameter
// so we will check if data by that parameter exists
$data = [];// initialization of array so we are sure $data is set
$this->load->model('Company_model');
$data['company_details'] = $this->Company_model->get_company($id);
if ($data['company_details']) {
$data['current_company'] = $this->Company_model->get_currentcomp($id) :'';
} else {
// in this point $data is an empty array
}
// $this way variable will be available in all view files
$this->load->var($data);
$this->load->view('includes/header');
$this->load->view('includes/left_menu');
$this->load->view('company/manage');
$this->load->view('includes/footer');
// so now, in your view you would have wether company with details wether an empty array
// *first line of code assumes parameter would be an integer
// **also assumed that $this->Company_model->get_company($id) would return false/null/anEmptyArray if data doesn't exist
}

Related

when I create a user the user details stored in user table as well as I have to insert the username into another table also

I get this error Illuminate/Database/QueryException with message 'SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value. But when MySQL turn to false I get my result but how can I do it on following way
User.php
public function deliverydetails()
{
return $this->hasOne(DeliveryDetails::class);
}
protected static function boot()
{
parent::boot();
static::created(function($user){
$user->deliverydetails()->create([
'billname' => $user->name,
]);
});
}
DeliveryDetails.php
public function user()
{
return $this->belongsTo(User::class);
}
viewpage
<div class="form-group">
<input type="text" id="billname" name="billname" value="{{$deliveryDetails->name}}" class="form-control" placeholder="Name">
<span style="color: red;">{{$errors->first('billname')}}</span>
</div>
productController
$deliveryDetailsCount = DeliveryDetails::where('user_id', $userid)->count();
if($deliveryDetailsCount > 0){
$deliveryDetails = DeliveryDetails::where('user_id', $userid)->first();
}
if(request()->isMethod('post')){
$this->validateDetails();
$data = request()->all();
// echo "<pre>"; print_r($data); die;
User::where('id', $userid)->update(['name'=>$data['name'], 'address'=>$data['address'],
'city'=>$data['city'], 'state'=>$data['state'], 'country'=>$data['country'],
'pincode'=>$data['pincode']]);
if($deliveryDetailsCount > 0){
//update address
DeliveryDetails::where('user_id', $userid)->update(['name'=>$data['billname'], 'address'=>$data['billaddress'],
'city'=>$data['billcity'], 'state'=>$data['billstate'], 'country'=>$data['billcountry'],
'pincode'=>$data['billpincode']]);
}
else{
//add new address
$c = new DeliveryDetails;
$c->user_id = $userid;
$c->email = $useremail;
$c->name = $data['billname'];
$c->save();
}
}
how can I solve the issue..

How to load database data to table using codeigniter

I want to display my database record in a table, but I don't get it. I don't know whats wrong in my code but it displays empty result. I have attached my model and view. I am using codeigniter framework. Any help would be much appreciated..
Here is my model:
public function display_data(){
$query = $this->db->query("SELECT * FROM sales_rep_tbl;");
if($query->num_rows > 0){
$this->table->set_heading(
"SR_Code",
"SR_Fname"
);
foreach($query->result() as $r){
$bg = "black";
$this->table->add_row(
"<div class = '".$bg."'>".$r->SR_Code."</div>",
"<div class = '".$bg."'>".$r->SR_Lname."</div>",
"<div class = '".$bg."'>".$r->SR_Fname."</div>"
);
$data.= $this->table->generate().br();
}
return $data;
}
}
And my view:
<div class = "container" >
<div class = "row" style = " height:400px; width:auto; margintop:20px;" >
<div class = "col-xs-12">
<?php echo $this->Main_Page_Model->display_data();?>
</div>
</div>
</div>
Please Follow the MVC structure of CI.
You Controller Should be:
public function veiw_table() {
$data= $this->yourModel->yourfunction();
$this->load->view('yourViewPage', ['data' => $data]);
}
Your Model Should Be:
public function yourfunction() {
$query = $this->db-
->select('*')
->get('yourTableName');
return $query ->result();
}
IN View:
foreach ($data as $singleData){
echo $singleData->columnNam;
}
Hope This will Help You

Display value in view

In this codeigniter model i have this query testing if value entered in input exists in database..
function get_search_form() {
$match = $this->input->post('search1');
$this->db->where('numero',$match);
$this->db->where('inscris','non');
$q = $this->db->get('transaction');
if($q->num_rows()>0)
{
foreach($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
Behold the controller i'd like to display value grabbed in input in view inscription.php
function search()
{
$data['row'] = $this->site_model->get_search_form();
$this->load->view('acceuil/aside');
$this->load->view('acceuil/inscription', $data);
}
My issue is how to display in that view input value and a form if this value exists in database ?
I have tried like this but i need help :
inscription view:
<?=form_open('navigation/search');?>
<input type="text" name="search1" id="search1" required />
<input type='submit' value='Display' />
<?=form_close();?>
I try to display the form like this but i don't know how to display as well the input value entered
<?php
if( $row > 0 )
{
?>
les champs du formulaire ici....
<?php
}else
{ }
?>
In your view you can check if the variable $row is not null (because it will be null when no rows are found):
if ($row !== null) {
// do stuff
}
You can modify the model function to return some other value if no rows are found, for example, by setting the $data to an empty array:
function get_search_form() {
$match = $this->input->post('search1');
$this->db->where('numero',$match);
$this->db->where('inscris','non');
$q = $this->db->get('transaction');
$data = array(); // <--- here
if($q->num_rows()>0)
{
foreach($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
And then in the view you can simply loop the data:
foreach($row as $r) {
// do stuff
}
or you can implode the array to use as the input value:
<input type="text"
name="search1"
id="search1" required
value="<?php echo implode(' ', $row); ?>" />
You could also use html entities here, in case double quotes are possible to appear in what your model function returns (I have no idea what it returns).
you can access $data global object like this check
<?php
if( isset($row))
{
foreach($row as $v){
//Do the operations here
}
}else
{
//Do the operations here
}
?>

Codeigniter. Controller cannot receive session data

I set session successfully as output profiler show me session name and value.
But when I POST data controller cannot receive session data.
Library is loaded, $config['sess_expire_on_close'] = TRUE I've changed TRUE-FALSE without any success. Also tried rewrite code.
And another question I use two PC and on Linux machine I get error "Header already sent...", but on Win machine I don't receive this message. How to enable it on Win PC. Notices and warnings are enabled.
So ...
Controller kmgld:
function authorisation_user()
{
......
$data['set_cookie'] = "Surname";
......
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->output->enable_profiler(TRUE); //show me only session name and value which I set
}
View:
if ($set_cookie!=NULL)
{
$this->session->set_userdata('surname',$set_cookie);
}
<!Doctype...>
<form action="<?php echo base_url()?>index.php/kmgld/update_kmgld" method="post" name="">
And again Controller kmgld
function update_kmgld()
{
...update DB
$test=$this->session->userdata('surname');
echo $test; //it is NULL
$this->output->enable_profiler(TRUE); // show me only now session id, ip, user agent
}
you have to set the userdata in the controller, the view isn't the proper place for it. so you probably would do something like this in your controller:
$surname = "Surname";
$this->session->set_userdata('surname',$surname);
$data['set_cookie'] = $surname;
...
$this->load->view('vheader', $data);
don't know if you autoload the session library. otherwise you have to load it in every function you need it.
remove session setting from view and do it in controller:
function authorisation_user()
{
$data['set_cookie'] = "Surname";
$this->session->set_userdata('surname',$set_cookie);
$this->load->view('vheader', $data);//are you sure here is where $data should go ?
$this->load->view('vuser_kmgld');//not $data here?
$this->output->enable_profiler(TRUE); //show me only session name and value which I set
}
Controller:
<?php
class Kmgld extends CI_Controller {
function index()
{
$data['flag'] = "first";
$this->load->model('Mkmgld');
$this->load->view('vheader');
$this->load->view('vauthorisation',$data);
$this->load->view('vfooter');
}
function get_kmgld()
{
$this->load->model('Mkmgld');
$this->Mkmgld->get_kmgld();
$this->load->view('vheader');
$this->load->view('kmgld');
$this->load->view('vfooter');
}
function authorisation_user()
{
$this->load->model('Mkmgld');
$surname_session = $this->session->userdata('surname');
$data['surname_post'] = mb_convert_case($this->input->post('surname'), MB_CASE_TITLE, "UTF-8");
$data['user_id'] = $this->Mkmgld->valid_user($data['surname_post']);
$surname = (isset($data['user_id'][0]->surname)? $data['user_id'][0]->surname: "");
if(isset($surname) and $surname !=NULL)
{
$data['query'] = $this->Mkmgld->get_kmgld($data['surname_post']);
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$data['set_cookie'] = $data['surname_post'];
$this->session->sess_destroy();
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->load->view('vfooter');
}else if (isset($surname_session) and $surname_session!= NULL)
{
//echo "you are in session";
$data['query'] = $this->Mkmgld->get_kmgld($surname_session);
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->load->view('vfooter');
} else
{
$data['flag'] = "wrong";
$this->load->view('vheader');
$this->load->view('vauthorisation',$data);
$this->load->view('vfooter');
}
//echo "<pre>";
//var_dump($data);
$this->output->enable_profiler(TRUE);
}//end authorisation_user()
function update_kmgld()
{
$this->load->model('Mkmgld');
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$trip_target_id = $data['get_trip_target_id'][0]->Auto_increment;
$this->Mkmgld->update_kmgld($this->input->post('day')
,$this->input->post('mon')
,$this->input->post('year')
,$this->input->post('spd_before')
,$this->input->post('spd_after')
,$this->input->post('total')
,$this->input->post('target')
,$this->input->post('approved')
,$this->input->post('user_id')
,$trip_target_id);
$a=$this->session->userdata('surname');
if ($a==NULL)
{
echo $a;
//redirect('kmgld/authorisation_user');
$this->output->enable_profiler(TRUE);
}
}
}//end class kmgld
?>
Model:
enter code here<?php
Class Mkmgld extends CI_Model {
function __construct()
{
parent::__construct();
}
function get_kmgld($surname){
$query = $this->db->query("SELECT
*
FROM `user`
INNER JOIN `user_has_trip`
ON `user`.`user_id` = `user_has_trip`.`user_id`
INNER JOIN `trip_target`
ON `user_has_trip`.`user_has_trip_id` = `trip_target`.`trip_target_id`
WHERE `user`.`surname` = '$surname'
");
return $query->result();
}
function valid_user($surname)
{
$user_id = $this->db->query("SELECT
*
FROM `user`
WHERE `user`.`surname`='$surname'
");
return $user_id->result();
}
function get_trip_target_id()
{
$get_trip_target_id = $this->db->query("SHOW TABLE STATUS LIKE 'trip_target'");
return $get_trip_target_id->result();
}
function update_kmgld($day, $mon, $year, $spd_before, $spd_after, $total, $target, $approved, $user_id, $trip_target_id)
{
$date = $year."-".$mon."-".$day;
$this->db->query("INSERT INTO `trip_target` (`trip_target_id`
,`date`
,`speedometer_before`
,`speedometer_after`
,`duration`
,`target`
,`approved`)
VALUES (NULL
,'$date'
,'$spd_before'
,'$spd_after'
,'$total'
,'$target'
,'$approved')
");
$this->db->query("INSERT INTO `user_has_trip`
(`user_has_trip_id`
,`user_id`
,`trip_target_id`
)
VALUES (NULL
,'$user_id'
,'$trip_target_id'
)
");
}
}//end class
?>
View vauthorisation:
<?php
$surname_value = $this->session->userdata('surname');
?>
<?php
if ($flag =="wrong")
{
echo "...Bad very bad. Try use another language ";
}
?>
html:
form method="post" action="authorisation_user"
input type="text" name="surname"
View vheader:
<?php
if ($set_cookie!=NULL)
{
$this->session->set_userdata('surname',$set_cookie);
echo "cookie set".$set_cookie;
}
?>
View vuser_kmgld:
html:
form action="update_kmgld"
inputs name=day, name=mon, name=year, name=spd_before...etc. After php code:
if (isset($user_id[0]->user_id))
{
foreach ($query as $row)
{
echo "<tr>
<td>".(isset($row->date)? date("d.m.Y", strtotime($row->date)): "")."</td>
<td>". (isset($row->speedometer_before)? $row->speedometer_before : "")."</td>
<td>". (isset($row->speedometer_after)? $row->speedometer_after : "")."</td>
<td>". (isset($row->duration)? $row->duration : "")."</td>
<td>". (isset($row->target)? $row->target : "")."</td>
<td>". (isset($row->aproved)? $row->aproved : "")."</td>
</tr>";
}
} //else redirect('kmgld/index');
?>

Component View displaying with 500 Internal Server Error

I have having issues following the tutorial of component development of Joomla. The tutorials I followed related to the issue are this and this.
I can view the default view properly, but when I click the new or edit and delete button, or when I browse too ../administrator/index.php?option=com_testimonials&view=testimonial&layout=edit I get that error.
I have rechecked the code so many times but I just can't find where I went wrong.
File: controllers\testimonial.php
class TestimonialsControllerTestimonial extends JControllerForm
{
//Nothing yet as per the tutorial
}
File: models\testimonial.php
class TestimonialsModelTestimonial extends JModelAdmin {
public function getTable($type = 'Testimonials', $prefix = 'TestimonialsTable', $config = array()) {
return JTable::getInstance($type, $prefix, $config);
}
public function getForm($data = array(), $loadData = true) {
// Get the form
$form = $this -> loadForm('com_testimonials.testimonial', 'testimonial', array('control' => 'jform', 'load_data' => $loadData));
if(empty($form)) {
return false;
}
return $form;
}
protected function loadFormData() {
// Check the session for previously entered form data
$data = JFactory::getApplication() -> getUserState('com_testimonials.edit.testimonial.data', array());
if(empty($data)) {
$data = $this -> getItem();
}
return $data;
}
}
File: views\testimonial\view.html.php
class TestimonialsViewTestimonial extends JView {
protected $form = null;
public function display($tpl = null) {
//get the data
$form = $this -> get('Form');
$item = $this -> get('Item');
$this -> form = $form;
$this -> item = $item;
$this -> addToolbar();
parent::display($tpl);
$this -> setDocument();
}
protected function addToolBar() {
JRequest::setVar('hidemainmenu', true);
$isNew = ($this -> item -> id == 0);
JToolBarHelper::title($isNew ? JText::_('COM_TESTIMONIALS_MANAGER_TESTIMONIAL_NEW') : JText::_('COM_TESTIMONIALS_MANAGER_TESTIMONIAL_EDIT'), 'testimonials');
JToolBarHelper::save('testimonial.save');
JToolBarHelper::cancel('testimonial.cancel', $isNew ? 'JTOOLBAR_CANCEL' : 'JTOOLBAR_CLOSE');
}
protected function setDocument() {
$isNew = ($this -> item -> id < 1);
$document = JFactory::getDocument();
$document -> setTitle($isNew ? JText::_('COM_TESTIMONIALS_TESTIMONIAL_CREATING') : JText::_('COM_TESTIMONIALS_TESTIMONIAL_EDITING'));
}
}
File: views\testimonial\tmpl\edit.php
<form action="<?php echo JRoute::_('index.php?option=com_testimonials&layout=edit&id='.(int) $this -> item -> id); ?>" method="post" name="adminForm" id="testimonial-form">
<fieldset class="adminForm">
<legend><?php echo JText::_('COM_TESTIMONIALS_TESTIMONIAL_DETAILS'); ?></legend>
<ul class="adminFormList">
<?php foreach($this -> form -> getFieldset() as $field): ?>
<li><?php echo $field -> label; echo $field -> input; ?></li>
<?php endforeach; ?>
</ul>
</fieldset>
<div>
<input type="hidden" name="task" value="testimonial.edit" />
<?php echo JHtml::_('form.token'); ?>
</div>
</form>
The problem is in your view folder name. Change testimonials folder name to testimonial as you have specified view=testimonial.
let me know if it does not work.
Update:
As discussed your table having naming problem-
class TestimonialsTableTestimonial extends JTable
{
public function __construct(&$db) {
parent::__construct('#__testimonial_table', 'id', $db);
}
function bind($array, $ignore = '')
{
return parent::bind($array, $ignore);
}
}

Resources