Pass a variable from controller to view when using form_open - php

I am very new to codeigniter and I was wondering if someone can help me. I want to pass a variable from my controller to my view, but the way I am do it it always give a undefined variable error. Also, if I keep the load->view call give an error too!
So, how can I pass the variable to the view? Thanks in advance to any help!
<?php <!-- view -->
echo form_open('match/setDefafultEmail', array(
'class' => '',
));
?>
<div class="well">
<div class="text-center">
<h4>Set Default Email</h4>
</div>
<?php
echo("<div>");
echo form_label('Email:');
echo form_input(array(
'id' => 'email_address',
'name' => 'email_address',
'type' => 'email',
'placeholder' => 'email#example.com',
'value' => set_value('email_address'),
'required' => '',
'title' => 'Email address'
));
echo("</div>");
echo("<div>");
echo form_submit(array(
'id' => 'btn',
'name' => 'min',
'type' => 'Submit',
'class' => 'btn btn-info',
'value' => 'Set Default Email'
));
echo("</div>");
echo form_close()
?>
<br>
<br>
<table class="table" >
<thead>
<tr>
<th>Name</th>
<th>Default Email</th>
</tr>
</thead>
<tr class="info">
<!--display current default name and email-->
<?php foreach($info as $row):?>
<td> <?php echo $row->full_name ?> </td>
<td> <?php echo $row->email ?> </td>
<?php endforeach;?>
</tr>
</table>
public function setDefafultEmail(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email_address', 'Email Address', 'valid_email');
if ($this->form_validation->run( ) == true){
$name = $this->input->post('full_name');
$default_email = $this->input->post('email_address');
$this->spw_vm_request_model->setEmailToDefault($name,$default_email);
}
$data['info'] = $this->request_model->getDefaultEmailAndName();
$this->load->view('admin/admin_dashboard',$data);
redirect('admin/admin_dashboard');
}

1) After you load the view you don't need to redirect. When you redirect('admin/admin_dashboard') you actually call the admin_dashboard Controller.
2) On your View you are trying to access an array as an object( $row->full_name ) I think you should use $row['full_name'].
3) In case your Model returns an object, you have to serialize it in your Controller and unserialize it in your View.

Related

stdClass error on CodeIgniter Comment System

I'm working on a comment section for my blog post in CodeIgniter, I based myself on a tutorial by Brad Traversy and I followed each step carefully but somehow it does not work within my template.
This is show method in my Post Controller:
public function show($slug)
{
// Get Posts by Slug
$data['posts'] = $this->Post_model->get_by_slug($slug);
// Get Comments per Post
$post_id = $data['posts']['id']; // Here is where I get the error
$data['comments'] = $this->Post_model->get_comments($post_id);
// If empty show a 404 error
if(empty($data['posts'])){
show_404();
}
// Load template
$this->template->load('public', 'default', 'posts/show', $data);
}
I created a variable $post_id in order to get the comments for the current post that is being visited by an user. All this should come from my Post_model:
public function get_comments($post_id){
$this->db->select('username,email,website,body');
$this->db->from('comments');
$query = $this->db->get_where('comments', array('post_id' => $post_id));
return $query->result_array();
}
This is where I'm creating the form to add the comment:
<!-- Form -->
<h4>Add a comment</h4>
<?php echo validation_errors('<p class="alert alert-danger">'); ?>
<?php echo form_open('public/comments/add_post_comment/'.$post['id']); ?>
<!-- Username -->
<div class="form-group">
<?php echo form_label('Username', 'username'); ?>
<?php
$data = array(
'id' => 'username',
'name' => 'username',
'class' => 'form-control',
'placeholder' => 'John Doe',
'value' => set_value('username')
);
?>
<?php echo form_input($data) ?>
</div>
<!-- Email -->
<div class="form-group">
<?php echo form_label('E-mail', 'email'); ?>
<?php
$data = array(
'id' => 'email',
'name' => 'email',
'class' => 'form-control',
'placeholder' => 'JohnDoe#demo.com',
'value' => set_value('email')
);
?>
<?php echo form_input($data) ?>
</div>
<!-- Website -->
<div class="form-group">
<?php echo form_label('Website', 'website'); ?>
<?php
$data = array(
'id' => 'website',
'name' => 'website',
'class' => 'form-control',
'placeholder' => 'https://www.example.com',
'value' => set_value('website')
);
?>
<?php echo form_input($data) ?>
</div>
<!-- Comments Body -->
<div class="form-group">
<?php echo form_label('Body', 'body'); ?>
<?php
$data = array(
'id' => 'body',
'name' => 'body',
'class' => 'form-control',
'placeholder' => 'Write here',
'value' => set_value('body')
);
?>
<?php echo form_textarea($data); ?>
</div>
<!-- Hidden Input -->
<?php
$data = array(
'name' => 'slug',
'value' => $posts->slug,
);
?>
<?php echo form_hidden($data); ?>
<!-- Submit Button -->
<?php echo form_submit('mysubmit', 'Add Comment', array('class' => 'btn btn-primary')); ?>
<?php echo form_close(); ?>
<?php endif; ?>
This is the Controller I'm using to add comments to the specific $post_id:
public function add_post_comment($post_id)
{
// Field Rules
$this->form_validation->set_rules('email', 'Email', 'trim|required|min_length[3]');
$this->form_validation->set_rules('body', 'Body', 'trim|required|min_length[3]');
if ($this->form_validation->run() == FALSE) {
// Set Message
$this->session->set_flashdata('error', 'There was an error in proccessing the comment. Please, try again.');
// Redirect to current page
redirect(site_url() . 'posts/show/'.$post_id);
} else {
// Get Post by Slug
$slug = $this->input->post('slug');
$data['posts'] = $this->Post_model->get_by_slug($slug);
// Create Post Array
$data = array(
'post_id' => $post_id,
'username' => $this->input->post('username'),
'user_id' => $this->session->userdata('user_id'),
'email' => $this->input->post('email'),
'website' => $this->input->post('website'),
'body' => $this->input->post('body'),
);
// Insert Comments
$this->Comments_model->add($data);
// Set Message
$this->session->set_flashdata('success', 'Your comment has been posted');
// Redirect to same page if form was not successful or submitted
redirect(site_url() . 'posts/show/'.$post_id);
}
}
All this should work according to some tutorials that I have seen before but this time is not.
The error comes from my function show. Any idea on how to fix this?
Thanks for helping.
Ok well as you would have read in the codeigniter users guide - $query->row() will return an object.
So you would use $data['posts']->id. Which may or may not work with your current PHP Version. I'm open to be corrected on that point.
If you want an associative array, as you are attempting to use, then you would use $query->row_array();
If you had performed a var_dump like...
public function show($slug)
{
// Get Posts by Slug
$data['posts'] = $this->Post_model->get_by_slug($slug);
// Quick Debug to Eyeball what is actually being returned.
var_dump($data['posts']);
exit();
// Get Comments per Post
$post_id = $data['posts']['id']; // Here is where I get the error
$data['comments'] = $this->Post_model->get_comments($post_id);
// If empty show a 404 error
if(empty($data['posts'])){
show_404();
}
// Load template
$this->template->load('public', 'default', 'posts/show', $data);
}
You would see ( and its always a good check when validating your code ) what is being returned by $this->Post_model->get_by_slug($slug);
It's a very good idea to know how to "look" at what your variables are and check they are what you think they should be.

function show in url after submit form in codeigniter

When I submit this form all things are well n good but I want the controller function not shows in url. I want all things are done in same page. Still the url show
localhost/Naveen/CodeIgniter/welcome/insertform
but I don't want the form_open('') show's in url so how it is possible?
controller welcome.php
public function insertform()
{
if (isset($_POST['mysmt']))
{
$this->form_validation->set_rules('fname', 'Name', 'required');
$this->form_validation->set_rules('femail', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('fmobile', 'Mobile', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('welcome_view');
}
else
{
$_POST['fname'];
$_POST['femail'];
$_POST['fmobile'];
if($this->test_model->insert('user_accounts',array('',$_POST['fname'],$_POST['femail'],$_POST['fmobile'])))
{
$success['success']="Thanks For Join Us";
$this->load->view('welcome_view',$success);
}
}
}
else
{
$this->load->view('welcome_view');
}
}
view welcome_view.php
<?php echo form_open('welcome/insertform'); // ?>
<div class="form-group">
<?php
if(isset($success))
{?>
<input type="button" class="form-control btn-success" value="<?php echo $success; ?>">
<?php }
else
{
echo "";
}?>
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">Name <?php echo form_error('fname'); ?></label>
<?php
$entername = array(
'name' => 'fname',
'value' => '',
'maxlength' => '100',
'placeholder' => 'Enter Name',
'class' => 'form-control',
);
echo form_input($entername); ?>
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">Email <?php echo form_error('femail'); ?></label>
<?php
$enteremail = array(
'name' => 'femail',
'value' => '',
'maxlength' => '100',
'placeholder' => 'Enter Email',
'class' => 'form-control',
);
echo form_input($enteremail); ?>
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">Mobile <?php echo form_error('fmobile'); ?></label>
<?php
$entermobile = array(
'name' => 'fmobile',
'value' => '',
'maxlength' => '100',
'placeholder' => 'Enter Mobile',
'class' => 'form-control',
);
echo form_input($entermobile); ?>
</div>
<div class="form-group">
<?php
$f_formsmt = array(
'name' => 'mysmt',
'value' => 'Submit Form',
'class' => 'form-control btn btn-success',
);
echo form_submit($f_formsmt); ?>
</div>
<?php echo form_close(); ?>
You handle it through applications/config/routes.php
consider you url: localhost/Naveen/CodeIgniter/welcome/insertform
$route['add'] = 'welcome/insertform';
now you can use localhost/Naveen/CodeIgniter/add
You can change whatever the string you want for any controller/function using routes.
Hope you understood :)
You need to add the url in route and add link to your link href
In route.php add:
$route['custom_url'] = 'controller/method';
I used Header("location:../{whatever-filename}")
Then gave that "whatever-filename" the proper routing in the config/routes.php.
Routing without using the redirect function would load the appropriate page but the url would still show the controller and method you're using.
Hope it helps

Data does not save and not displaying any error - Codeigniter

The data doesn't save without prompting any errors in my code
Here is my code in my Controller
function saveDebit(){
$jevseries=$this->input->post('series');
$account='debit';
$count='1';
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_rules('accountName', 'Account Name', 'required');
$this->form_validation->set_rules('amountDebit', 'Amount', 'required|numeric');
$this->formValidation();
if ($this->form_validation->run() == FALSE) {
$this->entryAccount($jevseries);
} else {
$debitData = array(
'Series' => $jevseries,
'AccountCode' => $this->input->post('accountName'),
'Account' => $account,
'Amount' => $this->input->post('amountDebit'),
'Count' => $count);
$this->Jev_model->entryDebit($debitData);
}
}
Model
function entryDebit($debitData){
$this->db->insert('generalaccount', $debitData);
}
This is my View
<?php echo form_open('Jev/saveDebit'); ?>
<table class="jev_entry" id="jev_entry">
<tr>
<td>Debit</td>
<?php echo form_hidden('series', $series);?>
<td><?php
$account_array = array();
foreach($accountNames as $account ){
$account_array []= $account->accountName;
}
echo form_dropdown('accountName', $account_array,'', 'class="form-control"');
?></td>
</tr>
<tr>
<td>Amount</td>
<td><?php echo form_input('amountDebit','', 'class="form-control"');?><div class="error"><?php echo form_error('amountDebit'); ?></div></td>
</tr>
<tr>
<td></td>
<td align="center"><?php echo '<center>'. form_submit('submit','Save').'</center>'; ?> </td>
</tr>
</table>
I don't know where is the error in this lines.. Your help is very much appreciated.
Okay i have found out what is wrong, The form_input of codeigniter only gives the form with a label. It does not give a name therefore we cannot post it since it doesn't have a name. Do this :)
$data = array(
'name' => 'username',
'id' => 'username',
'value' => 'johndoe',
'maxlength' => '100',
'size' => '50',
'style' => 'width:50%'
);
echo form_input($data);
It's like that and we post the name. Of course you can remove some parameters. More info in the form helper user guide in codeigniter :)
Godluck meyt

why jquery alert message not working accurately inside foreach loop?

When dropdown list box will be blank, I am trying to view message alert box by jquery in foreach loop but not working what can I do?
my cakephp code is below:
<?php
foreach ($data['customer'] as $index => $d):
$customer = $d;
$package = array();
if (count($data['package']) > 0) {
$package = $data['package'][$index];
}
?>
<tr class="odd gradeX">
<td><?php echo $customer['first_name'] . ' ' . $customer['middle_name'] . ' ' . $customer['last_name']; ?></td>
<td>
<ul>
<li>Cell:<?php echo $customer['cell']; ?></li>
<li>Address:<?php echo $customer['address'] ?></li>
</ul>
</td>
<td>
<?php if (count($package) > 0): ?>
<ul>
<li> Package Name: <?php echo $package['name']; ?></li>
<li> Month: <?php echo $package['duration']; ?></li>
<li> Charge: <?php echo $package['charge']; ?></li>
</ul>
<?php
endif;
?>
</td>
<td>
<?php
echo $this->Form->create('PackageCustomer', array(
'inputDefaults' => array(
'label' => false,
'div' => false
),
'id' => 'form_sample_3',
'class' => 'form-horizontal',
'novalidate' => 'novalidate',
'url' => array('controller' => 'admins', 'action' => 'changeservice')
)
);
?>
<?php
echo $this->Form->input('id', array(
'type' => 'hidden',
'value' => $customer['id']
)
);
?>
<?php
echo $this->Form->input('status', array(
'type' => 'select',
'id' => 'ddlist',
'options' => Array('ticket' => 'Generate Ticket', 'payment' => 'Customer Information', 'history' => 'Ticket History'),
'empty' => 'Select Action',
'class' => 'form-control form-filter input-sm',
)
);
?>
<br>
<?php
echo $this->Form->button(
'Go', array('class' => 'btn blue', 'id' => 'btnddlist', 'title' => 'Do this selected action', 'type' => 'submit')
);
?>
<?php echo $this->Form->end(); ?>
</td>
</tr>
<?php
endforeach;
?>
my jquery code is:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnddlist").click(function () {
var ddlist = $("#ddlist");
if (ddlist.val() == "") {
//If the "Please Select" option is selected display error.
alert("Please select a list data!");
return false;
}
return true;
});
});
By this code when I click first record button code working but others record button when I click not view alert box message!
that's because it is programmed to only respond to the first option:
if (ddlist.val() == "") {
//If the "Please Select" option is selected display error.
alert("Please select a list data!");
return false;
}
if you want to display your message (alert) on every option (for whatever reason, you can just remove the if condition of the above code, so you got only:
//changed: always displays message now.
alert("You selected something in the list!");
return false;
instead.

Echo current URL id in textfield in yii

I have a category,And I need to create a subcategory of that.
When i tried to create the subcategory i have a field called category Name which should preloaded with the name of category which i wish to create subcategory.
how can i achieve this..
My controller
public function actionCreate($id)
{
$model=new SubCategory;
$mode = Category::model()->findAll();
$mode_1=$this->loadModel1($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['SubCategory']))
{
$model->attributes=$_POST['SubCategory'];
if($model->save())
$this->redirect(array('create','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
And the form
<?php
/* #var $this SubCategoryController */
/* #var $model SubCategory */
/* #var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'sub-category-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>false,
)); ?>
<?php
$category_id = $_GET['id'];
$category = Category::model()->findByAttributes(array('id' => $category_id));
// echo '<pre>';print_r($category);'</pre>';
?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'category_id'); ?>
<?php echo $form->textField($model,'category_id',
array('class'=>'form-control','style'=>'width:300px;')); ?>
<?php echo $form->error($model,'category_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'subcategory_name'); ?>
<?php echo $form->textField($model,'subcategory_name',array('class'=>'form-control','style'=>'width:300px;')); ?>
<?php echo $form->error($model,'subcategory_name'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save',array('class' => 'btn btn-default')); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
<div style="width: 97%; margin: auto;" >
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'fav-category-grid',
'dataProvider'=>$model->search(),
//'filter'=>$model,
'columns'=>array(
// 'id',
//'favcategory',
array('header'=>'#','htmlOptions'=>array('width'=>'60px'),
'value'=>'$this->grid->dataProvider->pagination->currentPage * $this->grid->dataProvider->pagination->pageSize + ($row+1)',
),
//'id',
//'category_id',
array(
'name' => 'category_id',
'value' => '$data->category->categoryname',
//'filter'=> CHtml::listData(Category::model()->findAll(array('order'=>'categoryname')), 'categoryid', 'categoryname')
),
'subcategory_name',
array(
'class' => 'CButtonColumn',
'htmlOptions'=>array('width'=>'110px'),
'template' => '{update}{delete}',
'buttons' => array(
'update'=>array(
'imageUrl' =>false,
'label' => '',
'options' => array('title'=>'update','class'=>'btn btn-info btn-xs fa fa-pencil-square-o'),
),
'delete'=>array(
'imageUrl' =>false,
'label' => 'delete',
'options' => array('title'=>'view','class'=>'btn btn-danger btn-xs'),
),
)
),
),
'itemsCssClass'=>'table table-striped table-bordered table-hover',
'pagerCssClass'=>'pagination',
'pager'=>array( 'header' => '','lastPageLabel'=>'<span class="glyphicon glyphicon-chevron-right"></span><span class="glyphicon glyphicon-chevron-right"></span>','firstPageLabel'=>'<span class="glyphicon glyphicon-chevron-left"></span><span class="glyphicon glyphicon-chevron-left"></span>','prevPageLabel'=>'<span class="glyphicon glyphicon-chevron-left"></span>','nextPageLabel'=>'<span class="glyphicon glyphicon-chevron-right"></span>','header' => '','cssFile' => Yii::app()->baseUrl . '/css/pager.css','htmlOptions'=>array('class'=>'pagination'),'selectedPageCssClass'=>'active'),
)); ?>
</div>
I can see category model $category getting loaded in the form.
$category = Category::model()->findByAttributes(array('id' => $category_id));
And if id in category table is primary key, then I suggest, just for simplicity:
$category = Category::model()->findByPk($category_id);
Now I am guessing you may want that in textField which will be disabled.
So use textField() of CActiveForm in the form, something like:
$form->textField($category, 'name', array('disabled' => 'disabled'));
textField docs
Note: The second parameter must be the attribute name, I have assumed name.
Also I don't see the use of the following two lines in actionCreate(). I mean, the variable $mode and $mode_1 are not used anywhere in that action.
$mode = Category::model()->findAll();
$mode_1=$this->loadModel1($id);

Categories