CodeIgniter - 2 forms in a view - php

I have a view which has 2 forms:
<table>
<th>Write a comment.</th>
<tr>
<td>
<?php echo form_open($this->uri->uri_string(),$form1);
echo form_textarea($comment);
echo form_submit('submit','submit');
echo form_close();
?>
</td>
</tr>
</table>
<table>
<tr>
<td>
<?php echo form_open($this->uri->uri_string());
echo form_dropdown('portion', $portion_options);
echo form_submit('book','book');
echo form_close();
?>
</td>
</tr>
</table>
In the controller I check which button was clicked and then I perform some action by adding the corresponding form's values to the database.
if(isset($_POST['book']))
{
//sending the data to the database
echo "Book button clicked";
}
if(isset($_POST['submit']))
{
//sending the data to the database
echo "Submit button clicked";
}
However when the 'book' button is clicked no action is performed. It is like the button was never clicked. Whereas when I click the 'submit' button, every action is done properly.
In the past I have used the same technique on plain php (i mean no framework, just php), and has worked fine for me. Does codeigniter need any further configuration? Am I doing something wrong?

Why not add a hidden field to both forms called form_idwith values 1 and 2 respectively? Easy to catch in your controller upon post; e.g.:
if($this->input->post()){
switch($this->input->post('form_id')){
case 1:
// do stuff
break;
case 2:
// do stuff
break;
}
}

<?php echo form_open($this->uri->uri_string(),$form1);
and
<?php echo form_open($this->uri->uri_string());
Looks like you forgot to provide the settings in the second one like:
<?php echo form_open($this->uri->uri_string(),$form2);

Well after spending my whole day on this I finaly managed to solve it somehow (although I believe it is not such a propper way to handle this).
Well:
$comment = array(
'name' => 'comment',
'id' => 'comment',
'value' => 'write you comment',
'row' => '5',
'cols' => '100'
);
<table>
<th>Write a comment.</th>
<tr>
<td>
<?php echo form_open($this->uri->uri_string());
echo form_hidden('form_id', 1);
echo form_textarea($comment);
echo form_submit('submit','submit');
echo form_close();
?>
</td>
</tr>
</table>
<table>
<th>Write a comment.</th>
<tr>
<td>
<?php echo form_open($this->uri->uri_string());
echo form_hidden('form_id', 2);
echo form_dropdown('comment', $portion_options);
echo form_submit('book','book');
echo form_close();
?>
</td>
</tr>
</table>
Probably the forms fields (textarea and dropdown) needed to have the same name (which i have set to 'comment'). Although I do not understand why :/
Thank you all for trying to help me :)

Related

update table row and save in database in php codeigniter

I am making a table from a database and want to add an Edit/delete button to each row update or delete a specific row from the database. I have successfully added working "delete" button but I have no idea how could I update data in table <td> in view and send it to controller.
Here is my code:
view file
<table class="table table-striped">
<tr>
<td>name</td>
<td>age</td>
<td>gender</td>
<td>class</td>
<td>roll no.</td>
</tr>
<?php foreach($record as $r): ?>
<tr>
<td><?php echo $r->name; ?></td>
<td><?php echo $r->age; ?></td>
<td><?php echo $r->gender; ?></td>
<td><?php echo $r->class; ?></td>
<td><?php echo $r->roll no; ?></td>
<td><a href="" >Edit</a>
<a href="<?php echo base_url()."student/deleteRow" ?id="$r->name">"
onclick="return confirm
('Are you sure to Delete?')"><i class="icon-trash"></a></td>
</tr>
<?php endforeach; ?>
</table>
Controller Function
public function deleteRow(){
if(isset($_GET['id'])){
$id=$this->input->get('id');
$this->student_model->rowDelete($id);
redirect($_SERVER['HTTP_REFERER']);
}
}
I don't know how can I now insert an input field to update table row without effecting previous view. Any suggestion would be helpful.
To Edit the Studen data you need to pass an id or uniue column name to the data base to get that student data.
First Set the student id in <a href=""> tag.
<td><a href="<?= base_url('student/edit_student') ?>/$r->id" >Edit</a>
Then When you click on the edit it will take you to the controller. You can get the third url parameter direct in as show in the controler code:
You can also use get as shon
Your Controller should be:
public function edit_student($id){
$student_data = $this->student_model->get_student_data($id);
$this->load->view('your_view',['student_data'=>$student_data)]);
}
Here is you model which get the id form controllr and find the student data and passit to back to the controller:
Your Model should be:
public function get_student_data($id){
$this->db->select('*');
$this->db->from('your_table_name');
$this->db->where('id',$id);
$query = $this->db->get();
$student_data = $query->$row_array();
if(isset($student_data) && !empty($student_data)){
return student_data;
} else {
return FALSE;
}
}
Form controller you pass the data to the view.
On View Side:
<?php
// Just to ensure the data. Comment it after testing
echo "<pre>";
print_r($student_data);
echo "</pre>";
?>
<form action="<?= base_url('student/update_student') ?>/<?= $student_data['id'] ?>">
<input name="your_column_name" value="<?= $student_data['your_column_name'] ?>">
// Try to do the same for all you column.
<input type="submit" value="updata">
</form>
Here is the controller for update the data
public function update_student($id){
$student_data = $this->input->post();
$status = $this->student_model->update_student($id,$student_data);
if($status == TRUE){
$this->load->view('your_view');
// Your Success view
} else {
// Your view if fail to update
$this->load->view('your_view');
}
}
Here is the model for update the data
public function get_student_data($id,$student_data){
$this->db->where('id',$id);
$this->db->update('your_table_name',$student_data);
if($this->db->affected_rows() == 1){
return TRUE;
} else {
return FALSE;
}
}
Very similar to what you have done for delete. Something like this:
<td>
<a href="" >Edit/Delete</a>
<!-- This should be another method in Student controller -->
<i class="icon-trash"><!-- I changed order of edit and delete -->
</td>
I need to warn you for CSRF. If you don't implement better security here, anyone pointing to that link would be able to edit or delete data.
Check Security class in documentation and how to set hidden value so that way you would ensure that only one who has already requested that page was able to edit/delete rows.
<td><a href="<?php echo base_url();?>controller_name/function_name/<?php echo $edit_id;?>" >Edit</a></td>
another way
<td><a href="<?php echo base_url();?>controller_name/function_name?id=<?php echo $edit_id;?>" >Edit</a></td>
You can use any one according to your requirement.

PHP $_GET is empty trying first REST requests

trying to get my head around REST, I am following/copying a tutorial. The "$_get" is blank, I noticed that the URL that is being called is blank here is a copy,
http://localhost/RestClient/index.php?action=get_user&id=
but the href I am clicking looks ok to me.
<a href='http://localhost/RestClient/index.php?action=get_user&id='3' alt=user_'3'>Carbonnel</a>
here is my code I am new to PHP so figuring it all as I go!!!!
<?php
/*** this is the client ***/
if (isset($_GET["action"]) && isset($_GET["id"]) && $_GET["action"] == "get_user") // if the get parameter action is get_user and if the id is set, call the api to get the user information
{
$user_info = file_get_contents('http://localhost/RestServer/api.php?action=get_user&id=' . $_GET ["id"]);
$user_info = json_decode($user_info, true);
// THAT IS VERY QUICK AND DIRTY !!!!!
?>
<table>
<tr>
<td>Name: </td><td> <?php echo $user_info["last_name"] ?></td>
</tr>
<tr>
<td>First Name: </td><td> <?php echo $user_info["first_name"] ?></td>
</tr>
<tr>
<td>Age: </td><td> <?php echo $user_info["age"] ?></td>
</tr>
</table>
<a href="http://localhost/RestClient/index.php?action=get_userlist" >Return to the user list</a>
<?php
}
else // else take the user list
{
$user_list = file_get_contents('http://localhost/RestServer/api.php?action=get_user_list');
$user_list = json_decode($user_list, true);
// THAT IS VERY QUICK AND DIRTY !!!!!
?>
<ul>
<?php foreach ($user_list as $user): ?>
<li>
<?php echo "<a href='http://localhost/RestClient/index.php?action=get_user&id='".$user ['id']."' alt=user_'".$user['id']."'>"; ?><?php echo $user["name"] . "</a>"; ?>
</li>
<?php endforeach; ?>
</ul>
<?php
}
?>
The Link
<a href='http://localhost/RestClient/index.php?action=get_user&id='3' alt=user_'3'>Carbonnel</a>
is incorrect, it must be:
<a href='http://localhost/RestClient/index.php?action=get_user&id=3' alt='user_3'>Carbonnel</a>
Watch the changes in ' signs.
In you example $_GET['id'] must have been always null.
There is definitely something wrong with you <a>.
You are using single quotes for the tag attribute and then for query string parameters too.
Any program having to interpret that will have no idea where the href= actually ends.
One solution would be to use double quotes (") for the attribute and single quotes for the value (if you need those at all).
Change
<?php echo "<a href='http://localhost/RestClient/index.php?action=get_user&id='".$user ['id']."' alt=user_'".$user['id']."'>"; ?>
to
<?php echo "<a href='http://localhost/RestClient/index.php?action=get_user&id=".$user ['id']." alt=user_".$user['id']."'>"; ?>

multiple deleting with checkbox cakephp

I have a list of post and i want to delete them using multiple checkboxes.
I followed this link Multiple Check boxes in cake php
but i get this error(i use cakephp 2.4):
The view for PostsController::deleteSelect() was not found.
Confirm you have created the file: C:\xampp\htdocs\cakephp2\app\View\Themed\Cakestrap\Posts\delete_select.ctp
I want to access this data from index.ctp not from delete_select.ctp. My question is how i access this data "data['Post']['box'][]"?
My code is:
index.ctp
<?php foreach ($posts as $post): ?>
<tr>
<td><?php echo $post['Post']['id']; ?></td>
<td>
<?php echo $this->Html->link($post['Post']['title'], array('action' => 'view', $post['Post']['id'])); ?>
</td>
<td>
<?php echo $post['Post']['created']; ?>
</td>
<td>
<?php echo $this->Form->checkbox('post',
array(
'value' => $post['Post']['id'],
'name' => "data['Post']['box'][]",
));?></td>
<td>
<?php echo $this->Form->postLink(
'Delete',
array('action' => 'delete', $post['Post']['id']),
array('confirm' => 'Are you sure?'));
?>
<?php echo $this->Html->link('Edit', array('action' => 'edit', $post['Post']['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
<p><?php echo $this->Html->link('deleteSelect', array('action' => 'deleteSelect')); ?></p>
deleteSelect function
public function deleteSelect(){
if(!empty($this->data)) {
foreach($this->data['Post']['box'] as $key => $value){
$this->Post->delete($value);
}
$this->redirect(array('action' => 'index'));
}
}
you have to include all your checkboxes in a form if you want some data passed to your action.
But you can't do this since you are using Form::postLink that creates a form and you can't nest a form inside another form.
So you have to get rid of your postLinks. Are you sure you need them? Can't them all be simple links?
Once you have removed your postlinks then you can put all your code inside a big form
echo $this->Form->create('Post', array('action' => 'deleteSelect'));
// your foreach code here
echo $this->Form->end('Delete selected posts');
also: in your controller put this piece of code
$this->redirect(array('action' => 'index'));
outside the if condition
so the page will be redirected even if no data is passed (no checkbox is checked)
There is no post data
The last line of the view file is:
<p><?php
echo $this->Html->link(
'deleteSelect',
array('action' => 'deleteSelect')
);
?></p>
Unless there is some javascript listening for a click - that's just a link, not something which submits a form as such that means there is no form data. Given that, the relevant controller action does not enter the appropriate if and therefore attempts to render a view file:
public function deleteSelect(){
if(!empty($this->data)) {
...
// Unreachable
$this->redirect(array('action' => 'index'));
}
}
To prevent the problem mentioned in the question - simple don't make redirecting dependent on the presence of form data:
public function deleteSelect(){
if(!empty($this->data)) {
...
}
// Always executed
$this->redirect(array('action' => 'index'));
}
But that won't address the main problem that as written, it will simply do nothing.
Inputs need to be in a form
For inputs to do anything (ignoring the use of javascript) they need to be in a form. Therefore, the raw html needs to change from:
<table>
...
<input type="checkbox">
...
<input type="checkbox">
...
<input type="checkbox">
</table>
<p>
<a href="/deleteSelect" ...>deleteSelect</a>
</p>
To:
<form action="/deleteSelect" ...>
<table>
...
<input type="checkbox">
...
<input type="checkbox">
...
<input type="checkbox">
</table>
<input type="submit" value="deleteSelect">
</form>
I.e.:
Wrap the table in a form
Define the form action to go to the appropriate function
The link must change to a submit button.
In this way, the desired result can be achieved.
Warning - nested forms
Know that it's not valid to put a form inside another form. Therefore to get the "multi-delete" function to work using a normal form, will require removing the individual delete buttons since they are also embedded forms. An alternative technique to using postLink would be to make them normal links and use a simple javascript handler to prevent submitting via get, for example:
$('a.delete').click(function(e) {
if (confirm('Sure?')) {
$.post(this.attr('href')});
}
return false;
});
CakePHP requires that, if you're calling a function in a controller, you have a corresponding .ctp file, as noted.
To get around this you can use $this->autoRender = false; inside your method.
i have implemented it in my code just see my code.
<div>
<?php //echo $this->Form->create();
echo $this->Form->create(null, array(
'url' => array('controller' => 'manageParcels', 'action' => 'deleteParcel')
));
?>
<table width="100%" border="1">
<tr>
<th></th>
<th>Parcel Number</th>
<th>Consignment Number </th>
<th>Customer Name </th>
<th>Customer Address </th>
<th>Customer Phone-Number </th>
<th>Customer EmailId </th>
</tr>
<?php foreach($parcelDatas as $parcelData){
?>
<tr>
<td><input type="checkbox" name ="status[]" value="<?php echo
$parcelData['ManageParcel']['id']; ?>"></input></td>
<td align='center'><?php echo $this->html->link($parcelData['ManageParcel']
['parcelNo'], array('action' => 'editParcel',$parcelData['ManageParcel']['id']),
array('escape' => false));?> </td>
<td align='center'><?php echo $parcelData['ManageParcel']['ConNo']; ?></td>
<td align='center'><?php echo $parcelData['ManageParcel']['cusName']; ?></td>
<td align='center'><?php echo $parcelData['ManageParcel']['cusAddress']; ?></td>
<td align='center'><?php echo $parcelData['ManageParcel']['cusPhone']; ?></td>
<td align='center'><?php echo $parcelData['ManageParcel']['cusEmail']; ?></td>
</tr>
<?php
}?>
</table>
<?php
echo $this->Form->end(__('Delete Parcel')); ?>
</div>
**My controller code**
public function deleteParcel()
{
$this->autoRender=FALSE;
if ($this->request->is('post'))
{
if(empty($this->request->data))
{
$this->Session->setFlash(__('Please select parcel '));
return $this->redirect(
array('controller' => 'ManageParcels', 'action' =>
'listParcel')
);
}
$deleteParcels=$this->request->data['status'];
$size=sizeof($deleteParcels);
foreach ($deleteParcels as $deleteParcel)
{
$this->ManageParcel->id = $deleteParcel;
$parcelData=$this->ManageParcel->findById($deleteParcel);
if ($this->ManageParcel->delete()) {
$this->recordActivity('deleteParcel','Parcel
Number '.$parcelData['ManageParcel']['parcelNo'] . ' deleted' );
$this->Session->setFlash(__('Parcel data deleted'));
}
else {
$this->Session->setFlash(__('Parcel data was not Deleted'));
return $this->redirect(array('action' => 'listParcel'));
}
}
$this->recordActivity('deleteParcel',$size.' Parcels data deleted ');
return $this->redirect(
array('controller' => 'ManageParcels', 'action' => 'listParcel')
);
}
}

how to post the data with out click on checkbox in cakephp?

I have form where the select boxes are there and select all option, i want to post all the data without click on check boxes, i dont want to view this page, mean if user go to signup page the data will already selected by default how can i do that wothout any view?
this is my view code
<?php v_start($this);?>
<?php
#if(element exits of controller-action)
echo $this->element('validations/users/signup');
?>
<script>
function toggleChecked(status)
{
jQuery(".new-checkbox input").each( function() {
jQuery(this).attr("checked",status);
}
)
}
</script>
<h1><span style="color:CornflowerBlue"><?php echo __l('Step1');?></span></h1>
<?php
$form = $this->FormManager;
echo $form->create('User',array_merge($form_options,array('default'=>true)));
?>
<table width = "100%">
<tbody>
<tr>
<td>
<?php echo $form->input('',array('id'=>'mark-all','onclick'=>'toggleChecked(this.checked)','type'=>'checkbox','label'=>'Select All Products' ));?>
<?php echo $form->input('product_id',
array(
'multiple'=>'checkbox',
'options'=>$products,
'div'=>false,
'class'=>'new-checkbox'
)
);
?>
</td>
</tr>
<tr>
<td>
<?php
echo $this->FormManager->end(LBL_BTN_NEXT);
?>
</td>
</tr>
</tbody>
</table>
i dont want this page, the user will select the data by default.
this is my controller code
$products = $this
->User
->ProductsUser
->Product
->find('list',array(
'fields' => 'product_id,name',
'conditions'=>array(
'Product.is_visible'=>true
)
)
);
$this->set('products',$products);
if($this->request->is('post'))
{
$this->Session->write('signUp.signUpProduct',$this->request->data['User']);
$this->redirect(array('action'=>'signup_product'));
}
}
how can i do that, Thanks in advance.
The attr() doesn't take true or false as an argument.
jQuery(this).attr("checked","checked"); // Correct usage of attr()
Although I think attr is deprecated for the favorable prop() method.
jQuery(this).prop("checked",status);
Which indeed does take a true/fales argument. :)
Hope this helps.

passing a php array item into a javascript popup window to be edited and updated in mysql db

I am creating a diabetes management system for a university project. One of the features of this system is for the patient to be able to send latest glucose readings and for the nurse to be able to login and comment on those readings.
I have been able to code the patient feature, however I wish to add a comment button in the comments column, which when clicked, brings up a popup window or a textbox for the nurse to be able to comment on that specific record. If a comment has not already been entered, an empty box should come up, however if there has been a previously entered comment, it should be displayed in the box to be updated and sent back to the mysql database. I would like to ask if someone could give me a way to include this comment box and code for the existing value to be displayed in the box and if there is no existing comment, then a new comment can be entered and stored in the database.
Below is my php code.
<?php//run query
$result = mysql_query($GetReadings);
?>
<table>
<tr>
<th>Date</th>
<th>Time</th>
<th>Glucose Level</th>
<th>SBP</th>
<th>DBP</th>
<th>Comments</th>
</tr>
<?php
//display results
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<tr>
<td><?php echo $row["Date"]; ?> </td>
<td><?php echo $row["Time"]; ?> </td>
<td><?php echo $row["GlucoseLevel"]; ?> </td>
<td><?php echo $row["SBP"]; ?> </td>
<td><?php echo $row["DBP"]; ?> </td>
<td><?php echo $row["Comments"];
<?php
//if statement to add comment link if user is a nurse
if ($_SESSION['User_level'] == 2)
{
//code for comments
}
?> </td>
</tr>
<?php
//end of while loop
}
?>
Hope I haven't missed out any crucial information.
Use the javascript function :
window.open(URL, windowName[, windowFeatures])
Where, URL - desired URL to display a page containing Textbox, use any window name you want.
Echo <a> or button with a onclick event eg:
Add Comment
Edit
The most basic way to achieve is, echo a <div></div> containing the past comments, the text box for new comments and Send/Cancel buttons. The trick is to set the display:none style property of that div. You the following code a guideline :
Echo the following code if the User has right user level.
Show Comments
<div id="comment-<?php echo $row['id']?>" style="display:none">
//display previous comments
<form method="post" action="addComment.php?id=<?php echo $row['id']?>">
<textarea name="comment"></textarea>
<input type="submit" value="Add Comment" /><input type="button" onclick="hideComment('<?php echo $row['id']?>')">
</form>
</div>
<script type="text/javascript">
function hideComment(id) {
document.getElementById('comment-' + id).style.display = 'none';
}
function showComment(id) {
document.getElementById('comment-' + id).style.display = 'block';
}
</script>

Categories