Best way for form action? - php

I just started using Code Igniter framework and also just started learning on PHP OOP. I came across something when coding for the forms.
In a form if I have two buttons that would lead to different pages, what would be the most suitable way to do it? I found two ways. The first is to have a dynamic action/link, let's call it method A:
Method A
Variable $form_link is 'form_link'.
(View) main_user_view.php
<?php echo form_open($form_link); ?>
<?php echo form_button($add_user_button); ?>
<?php echo form_button($delete_user_button); ?>
<?php echo form_close(); ?>
(Controller) User.php
public function form_link()
{
// Value of button clicked
$form_submitted = $this->input->post('submit_form');
if($form_submitted == 'add_user')
{
redirect('User/add_user');
}
elseif($form_submitted == 'delete_user')
{
redirect('User/delete_user');
}
elseif($form_submitted == 'back')
{
redirect('User');
}
}
And the other way is instead of having a second button I would use an anchor and make an absolute path for it.
Method B
Variable $form_link is 'add_user' which is a function in the controller.
(View) main_user_view.php
<?php echo form_open($form_link); ?>
<?php echo form_button($add_user_button); ?>
<?php echo anchor('add_delete_user/delete_users_view', 'Delete', array('class'=>'btn btn-info', 'role'=>'button'));?>
<?php echo form_close(); ?>
The only problem I have with method A is that if in the form I have input fields, I cannot get the data through POST as redirect does not carry over the data to other functions. I resolved that by using method B where the anchor would lead to the function I want whereby I can get the POST data.
So my main question is, should I use method B instead whenever I have two or more buttons in a form?

You have to use button names for form post actions,
public function form_link()
{
if($this->input->post('add_user'))
{
redirect('User/add_user');
}
if($this->input->post('delete_user'))
{
redirect('User/delete_user');
}
}

What my opinion is also to use the Method B. To make the URL more nicer you can use custom routing (which is located at 'application/config/routes.php')

Related

View included by $this->include does note recieve passed params

Is possible pass parameter to view when i use $this->include method in another view?
In example:
<?php
foreach ($destaques as $camping) {
$this->include('partial', ['camping' => $camping])
}
?>
But partial.php dont recieve $camping value.
When using $this->include you're making an echo of a view into an other one. So by default, the view you're loading will have acces to any data you gave to the parent view but not variables you declared into it.
A few options in your case :
Using the view method :
foreach ($destaques as $camping) {
echo view('partial', ['camping' => $camping]);
}
Moving your foreach loop in the partial view so you'll use $destaques into it.
<?php
// dont forget to echo
echo $this->include('partial')
?>
// or this way with short tags enabled
<?= $this->include('partial') ?>
And just embed your partial view in your previous foreach loop
foreach ($destaques as $camping) {
// whatever your partial view is
}
Hello I try using the parameter option. I test code and it s working. But note the include view layout method work like php default include function and it does not display until you echo it.
Here is my code which I use to test yours and it worked for me. Check it
$inc = '';
foreach ($destaques as $camping) {
$inc .= $this->include('partial', ['camping' => $camping])
}
echo $inc;
And this displayed and worked for me check it. if this is not what you were expecting, just call my attention

Whether following types of code can be present in view in mvc(codeigniter)?

I am new to MVC & codeigniter and want to know whether its okay to have following types of code in view files
if(strcasecmp($_SESSION['role'],'author')==0)
{
some code
}
or
if($this->session->flashdata('edition_done_by'))
{
some code
}
i.e. checking existence of a session object or flashdata in a view file
Also,I would want to know whether creating table rows dynamically in a view file using foreach loop construct(like given below) is alright as per MVC
<?php foreach($items as $item){ ?>
<tr>
<td><?php echo $item->name; ?> </td>
<td><?php echo $item->price; ?> </td>
</tr>
<?php } ?>
Its not a good practice to check session values within the view. Check it within controller and pass the relevant data to view
It goes completely against the idea of the Model-View-Controller principe.
In (really) short; the model is responsible for managing data entities, CRUD operations, how a data entity should look like, etc. The controller is responsible for any business logic. Which means; when should I update a record, should this data be available to user x, etc. The view is merely responsible for displaying data that is already available. Nothing more, nothing less.
So in your example; the Controller should check session data, flash data, whatever, and send the processed data to the view. Eg:
if( strcasecmp($_SESSION['role'],'author') === 0 )
{
$can_edit = true;
$message = 'You can edit! Go ahead';
} else {
$can_edit = false;
$message = 'You do not have sufficient rights to edit this entity';
}
Now pass these variables to the view, there you can do something like:
<?php if ( $can_edit ): ?>
<form action="POST">
<p><?php echo $message; ?></p>
<textarea name="content"><?php echo $entity->content; ?></textarea>
<button type="submit">Update</button>
</form>
<?php else: ?>
<p><?php echo $message; ?>
<?php endif; ?>
One Word Answer is Yes! No Problem
It is fine to access Session Variables in Views . Session are variable to store information.
As Long as you are not putting Business Logic Inside Your View . you can use anything in views . The Case you mentioned you are using is What I will call "Display Logic" that is used to check which / What /From Where/ How content will be shown .
From Two Code Samples you Show Following One is Correct to Use with MVC
if($this->session->flashdata('edition_done_by'))
{
some code
}
You For Loop Code is also having no problem with MVC

Unable to insert data with CodeIgniter

I am making a website in CodeIgniter and for one of these pages I need to insert information into a database, however every time I enter information into my form and submit it, the page refreshes like it had been submitted but nothing enters the database.
Controller:
public function insertjob()
{
$this->load->helper('form');
$data['title']="Add a new job";
$this->load->view("insertjob", $data);
}
public function addingjob()
{
$jobtype=$this->input->post('jobtype');
$jobinfo=$this->input->post('jobinfo');
$this->load->model("cmodel");
if($this->cmodel->addjob($jobtype, $jobinfo)){
$data['msg']="New job addition successful";
}else{
$data['msg']="There was an error please try again";
}
$this->load->view("confirmation",$data);
Model:
function addjob($jobtype,$jobinfo)
{
$newjob=array("jobtype"=>$jobtype,"jobinfo"=>$jobinfo);
return $this->db->insert('clientjobs', $newjob); exit;
View:
</p>
<?php
echo form_open('client/insertjob');
echo form_label('Job:', 'Job');
echo form_input('jobtype');
echo form_label('Job information:', 'Job information');
echo form_input('jobinfo');
echo form_submit('Add job', 'Submit Post!');
echo form_close();
?>
Try removing the exit from your model:
function addjob($jobtype,$jobinfo)
{
$newjob=array("jobtype"=>$jobtype,"jobinfo"=>$jobinfo);
return $this->db->insert('clientjobs', $newjob);
}
It's not neccessary and could be breaking the database class, as well as halting any execution for the application.
Here's your problem:
echo form_open('client/insertjob');
If you look at your HTML code in your browser, you'll see something like this:
<form action="client/insertjob">
There will probably be a whole bunch of other attributes in your form tag - they're not important for this answer.
That action attribute is telling the browser where to go after you click submit. Where is it going? Back to the insertjob method. But it needs to go to your addingjob method - that's where the database update is actually being done. So change the form_open call to:
echo form_open('client/addingjob');
As I see your are using 2 controller functions for posting, page 1 to page 2. You have error on form open you should post your data to addingjob not insertjob.
echo form_open('client/addingjob');
will fix your issue but I highly recommend you to use, one controller for form submit. Below code will send post to same url. And you could add some attributes on it.
<?php
$attributes = array('class' => 'form-horizontal');
echo form_open($this->uri->uri_string(),$attributes); ?>

Reset dropbox automatically to first value after the users hit submit button PHP

After the user hits the submit button, how do I reset the drop down menu to the "blank" option of the the menu? I am using a MVC set up with php and HTML, and the concrete5 library. THANKS IN ADVANCE! Here is what I have so far:
Controller code:
public function authorize() {
$selectHost = array('' => '');
foreach ($this->host->getHostInfo() as $row) {
if (isset($row['HARDWARE_id'])) {
$selectHost[$row['id']] = $row['host'];
}
}
$this->set('selectHost',$selectHost);
$postCheck=array(array('param' => 'host',
'check' => '^[0-9]{1,50}$',
'error_msg' => 'Invalid Host ID'),
);
$post = scrub($_POST,$postCheck);
if (isset($post['host'])) {
$this->host->authorize($post['host']);
$this->set('test', "<p> The host has successfully been authorized.</p>");
}
else{
$this->set('failed', "<p>Invalid Host ID</p>");
}
}
view code:
<form method="post" enctype="multipart/form-data" action="<?=$this->action('authorize')?>">
<?php
$form = Loader::helper('form');
print $form->label('host', 'Host: ');
print $form->select('host', $selectHost);
?>
<?php
print $form->submit('Submit','Submit');
echo $test;
echo $failed;
?>
</form>
I'm pretty positive that there's no way to override C5's desire to take the POSTed value and use that as the default. Even if, as TWR suggested, you specify a value. (This is typically a good thing, because if the page is POSTed to and there's an error, you don't want to show the value from the database; you want to show what was in the POST).
You can override the form helper pretty easily.
However, I'd suggest that you do a redirect after successful submission (don't redirect after an error -- then the POSTed value will be useful) to a page. You can redirect to another page, or the same one, ideally with a confirmation message. See https://github.com/concrete5/concrete5/blob/master/web/concrete/core/controllers/single_pages/dashboard/blocks/stacks.php#L23 for an example of using redirect.
This is the best practice for your problem but also because, with your current code, if somebody hits refresh, it'll rePOST the data and reauthorize the host.
i think you could extend the form tag with a (javascript) onsubmit action which does the reset.
Since it's a form submit, you just want to change the value of the "drop box"/select in your view. After a submit, you'll have a fresh page load; so, in every case you'll want to display the default value, and not the current value of $selectHost
In your view, change this
print $form->select('host', $selectHost);
to this
print $form->select('host', $selectHost, null);
According to http://www.concrete5.org/documentation/developers/forms/standard-widgets
If the problem is that the Concrete5 form helpers are not behaving as you want, then just don't use them -- instead just use regular HTML form inputs instead.
<form method="post" enctype="multipart/form-data" action="<?=$this->action('authorize')?>">
<label for="host">Host: </label>
<select id="host" name="host">
<?php foreach ($selectHost as $value => $text): ?>
<option value="<?php echo htmlentities($value); ?>"><?php echo htmlentities($text); ?></option>
<?php endforeach; ?>
</select>
<input type="submit" value="Submit" />
<?php
echo $test;
echo $failed;
?>
</form>

passing variables between functions and files in php

I have a file called admin.php in which I have a button with the name send. What I want to do is when I click it, to make visible a link on the user's page, user.php. How can I do this?
I have a file with all my functions called functions.php in which I have a function called onSubmit($var); I initialize the variable $var is admin.php with the value $_POST['send'] but when I call the function in the file user.php I have no way of telling him who the variable $var is so I get 'undefined index'.
Is there another way to do this?
EDIT Added code
This is admin.php
<input type="button" name="send" value="Submit" /><br/>
require 'functions.php';
$posted = $_POST['send'];
onSubmit($posted);
This is user.php
require 'functions.php';
onSubmit($var); //here it says undefined index var because it doesn't know who the variable is
if($isSent == 1) {
<a style="visibility:visible;" href="test3.html" id="test3">Test3</a> <br/>
}
And this is functions.php
global $isSent;
function onSubmit($var) {
if(isset($var)) {
$isSent = 1;
}
}
Basically you need to use sessions like below:
if(isset($_SESSION['makeVisible']) && $_SESSION['makeVisible'] == true){
echo '<button>Button init</button>'; //you could also use html like the comment below.
}
/*
if(condition){?> <!-- this is now html --> <button>Button init</button><?}
*/
Then to set this variable on your admin page use:
if(isset($_POST['submitButton'])){
$_SESSION['makeVisible'] == true;
}
You'll also need a form for this method to work but there are other methods but I prefer this one.
<form name="buttonMakerThing" method="POST">
<input name="submitButton" value="Make button init Visible" type="submit"/>
</form>
Without an action the form defaults to 'POSTING' the form information to the current page. Making the condition if(isset($_POST)) return true.
You will need to add a $_SESSION declaration at the top of every php page you have on your site for this to work. It MUST go on the very first line of every page! for example:
01: | <?php session_start();
02: |//rest of script;
Please look more into $_SESSIONS for unnsetting/destroying your sessions and more uses for them :) http://php.net/manual/en/reserved.variables.session.php
Right I've done a bit of research on Caching and this is what I've come up with. It might not be 100% correct but it's a start as like I've said I've never tried it myself lol
In your admin.php I'd put this function in:
if(isset($_POST['send'])){
if($enabled == true){
$enabled == false;
}
else{
$enabled == true;
}
apc_add('enabled',$enabled);
}
Now to 'get' our $enabled var:
$enabled = apc_fetch('enabled');
Then to check the the var within your client page:
if($enabled == true){
echo ' button';
}
Now the only things I haven't fully looked at is the security of the apc_ function and the client usage. I believe it works for all clients of the server but I'm not 100% certain. Here the php manual to give better examples.
This is the method I was thinking of. But again I'm not sure on the security of it but I'm sure you can find something to keep it secure. The video is actually is tutorial for a Youtube API. But he does cover saving a variable to a cache text file which should be of use to you :)
If you have functions.php which defines functions, simply include it in admin.php file and then you can call the function from there and also pass value.

Categories