I have this contact form with codeigniter, and what I want to do is, when the form is submitted but does not pass validation, I want the fields to contain earlier submitted values.
There's one thing though: when the form is loaded all the fields already have a certain value assigned, so for example the "name field" shows "name" inside the field. And I want this to stay that way, unless "name" is changed and the form is submitted, in that case it should have the new value.
So for the moment I have this:
<?php echo form_input('name', 'Name*');?>
<?php echo form_input('email', 'Email*');?>
But I don't know how to make the form remember any new submitted values.
Anyone any idea?
I'd recommend using CodeIgniter's set_value method.
<?php echo form_input('name', set_value('name', 'Name*')); ?>
I think the answer lies in the controller.
Personally, I started letting the forms controller function handling the validation:
<?php
class Page extends Controller
{
...
function showform()
{
$this->load->helper(array('form', 'url'));
$data = array("name" => "Name*", "email" => "Email*");
$failure = false;
if( $this->input->post("name") )
{
$data["name"] = $this->input->post("name");
$data["email"] = $this->input->post("email");
if( !valid_email($data["email"]) )
{
$failure = true;
$data["error_message"] = "E-mail couldn't validate";
}
if( !$failure )
redirect('/page/thankyou/', 'refresh');
}
$this->load->vars($data);
$this->load->view("theform");
}
...
}
And in your view, you would do something like this:
<?php echo form_input('name', $name);?>
<?php echo form_input('email', $email);?>
If you are submitting to the same controller, you can get the previously submitted variables through $_POST (or $_GET depending on which form method you chose).
// use $_POST['name'] if set, else use 'Name*'
<?= form_input('name', (!empty($_POST['name']) ? $_POST['name'] : 'Name*'); ?>
Related
I have tried several solution posted in this forum and others as well but it has not helped so far. So I am posting my question finally. BTW, I am using CakePHP 3.6.
I am trying to pass a variable ($product->id) via submit button in view.ctp to my controller action "addit" but I just get "Undefined variable: id " (I have tried addit($id) and addit() either of case I have the same result.)
view.ctp
<p>
<?php echo $this->Form->create('NULL',['url'=>['controller'=>'products','action'=>'addit']]);?>
<?php echo $this->Form->input('id', ['type' => 'hidden', 'value' => $product->id]); ?>
<?php echo $this->Form->button('Add to cart now');?>
<?php echo $this->Form->end();?>
</p>
Controller:Products
public function addit() {
$this->autoRender = false;
if ($this->request->is('post')) {
// $this->Products->addProduct($this->request->data['Cart']['product_id']);
echo "".$this->Products->get($id);//for test
} else {
echo "".$this->Products->get($id);//for test
}
}
According to Cakephp 3.6
All POST data can be accessed using
Cake\Http\ServerRequest::getData(). Any form data that contains a data
prefix will have that data prefix removed. For example:
// An input with a name attribute equal to 'MyModel[title]' is accessible at
$title = $this->request->getData('MyModel.title');
You can get value of $id variable like this:
$id = $this->request->getData('id');
Further Reading: Request Body Data
Is this what you want to do?
$id = $this->request->getData('id');
debug($this->Products->get($id)); //for test
I am trying to send an httpRequest to a codeigniter controller function. I am using the REST console to test the function .
I am trying to send 3 POST variables .
UserName
Email
UserID
Here's the code to handle the request
public function NewUser()
{
if($this->input->post())
{
$FID = $this->input->post('UserID');
$UserName = $this->input->post('UserName');
$Email = $this->input->post('Email');
echo "working";
echo $FID;
echo $UserName;
}
else
{
echo "not working";
}
}
But this doesn't work. It always output's not working. When I change everything to geteverything starts working fine.
What could be the issue ? Post Request is not working anywhere throughout this codeigniter project.
EDIT
I created a new script, with the following code.
<?php
var_dump($_POST);
echo $_POST['UserName'];
echo $_POST['FacebookID'];
echo $_POST['Email'];
echo "********************************";
?>
It is saying undefined index . What could be the issue ? Please help. It works fine for $_GET
$this->input->post() is obliviously return the false because you are not mentioning the name of which value you want to retrieve using post.Make changes here in your code :
if(isset($_POST))
or
if(!empty($_POST))
See POST
you can also do this:
if($this->input->post('username'))//username is the name of post variable
you should try
isset($_REQUEST)
or
!empty($_REQUEST)
to check data is coming or not
To get the method in codeigniter 3 (docs) you can use the following code:
echo $this->input->method(TRUE); // Outputs: POST
echo $this->input->method(FALSE); // Outputs: post
echo $this->input->method(); // Outputs: post
example:
public function NewUser()
{
if($this->input->method() === 'post')
{
$FID = $this->input->post('UserID');
$UserName = $this->input->post('UserName');
$Email = $this->input->post('Email');
echo "working";
echo $FID;
echo $UserName;
}
else
{
echo "not working";
}
}
Try
if( count($this->input->post()) > 0 )
{
}
else
{
}
I had a similar problem. Due to using internationalization, URLs get redirected from user/login to user/en/login. When that redirect happens, the POST array gets lost.
I am not sure if this is your problem as well, but check if your page redirects after submission.
In Codeigniter we can check which HttpRequest it is using 2 below Input class' method :
1. server('REQUEST_METHOD')
$this->input->server() is identical to Core PHP's $_SERVER variable.
example:
if ($this->input->server('REQUEST_METHOD') == 'GET') {
echo "It's GET Request";
} else if ($this->input->server('REQUEST_METHOD') == 'POST') {
echo "It's POST Request";
}
2. method()
Since Codeigniter 3 we can use method() also for checking request type.
method([$upper = FALSE])
Parameters:
$upper (bool) – Whether to return the request method name in upper or lower case
Returns: HTTP request method
Return type: string
explanantion: It Returns the $_SERVER['REQUEST_METHOD'], with the option to set it in uppercase or lowercase.
example:
echo $this->input->method(TRUE); // Outputs: POST
echo $this->input->method(FALSE); // Outputs: post
echo $this->input->method(); // Outputs: post
I cannot get the hidden value of form if it is hidden.
My form view:
<?php echo form_input(array(
'class'=>'emp_name',
'name'=>'emp_name',
'id'=>'emp_name',
'value'=>'')
);?>
<?php echo form_hidden('emp_id', ''); ?>
I set employee name by using jquery autocomplete and then set the emp_id value to the returned ID with the name.
My Controller:
$data = array(
'emp_id'=>$this->input->post('emp_id')
);
This conroller is the form of my view above. I can get the emp_name properly but not the emp_id because it is hidden, if I do not use hidden it works fine. Any idea how can I hide the ID by getting the value in my conntroler?
It looks like you are not submitting the form to the system.
You need to open/close and submit the form.
Quick little test:
class Test_form extends CI_Controller
{
function __construct()
{
parent::__construct();
//displays the profiler info to make debugging easy
$this->output->enable_profiler(TRUE);
}
function test_form()
{
echo form_open();
echo form_input(array(
'class'=>'emp_name',
'name'=>'emp_name',
'id'=>'emp_name',
'value'=>'')
);
echo form_hidden('emp_id', '');
echo form_submit();
echo form_close();
}
}
I'm trying to send POST values to the controller and then pass it to the model in PHP but I'm not sure how to go about doing this.
This part of the controller is to see if the user requests for a view like ?action=game. This works.
But I'm trying to modify it to allow $_POST to be sent to it and then to the model.
function __construct()
{
if(isset($_GET['action']) && $_GET['action']!="" )
{
$url_view = str_replace("action/","",$_GET['action']);
if(file_exists("views/" . $url_view . ".php" ))
{
$viewname = $url_view;
$this->get_view($viewname . ".php");
}
else
{
$this->get_view('error.php');
}
}
else
{
$this->get_view('home.php');
}
}
Here's what I got. In the registration form page, the action of the form is ?process=register but it doesn't work.
if(isset($_POST['process']) == 'register)
{
$this->get_view('register.php')
}
Get_view function determines what model to bind with the view
function get_view($view_name)
{
$method_name = str_replace(".php","",$view_name);
if(method_exists($this->model,$method_name))
{
$data = $this->model->$method_name();
} else {
$data = $this->model->no_model();
}
$this->load->view($view_name,$data);
}
Since the action of your form is ?process=register, then process is still in the $_GET superglobal. What you can do to make it use post is add a hidden input field containing process.
With this:
<form method="post" action="script.php?process=register">
The form is POST'ed to script.php?process=register so you have $_GET['process'], not $_POST['process'].
Try this instead:
<form method="post" action="script.php">
<input type="hidden" name="process" action="register" />
To have $_POST['process']. Alternatively, you could keep the "process" in the GET and switch your if statement to check $_GET instead of $_POST.
I have two CHtml::submitButton() in my form, namely "Accept" and "Reject". Each of the buttons has a specific ID ... When any of the two are pressed, i would like to trigger an action in my controller. Below are the code snippets.
=========================================================
View
<?php
echo CHtml::beginForm('mycontrollerName/AcceptUserRegistration','get');
?>
<?php echo CHtml::submitButton('Accept', array('id' => 'accept')); ?>
<? echo ' '; ?>
<?php echo CHtml::submitButton('Reject', array('id' => 'reject')); ?>
<?php echo CHtml::endForm(); ?>
========================================================
Controller
public function actionAcceptUserRegistration() {
$value = $_GET['id'];
if($value == "accept"){
//will do something here
}
if($value == "reject"){
//will do something here.
}
}
======================================================================
When i implement it this way. the get value in the controller side is empty. What I'm I doing wrong? Or is there any other way around this?
You forgot to give the submit button a name (unless your framework does some magic which we cannot know about - you should really post the generated HTML code!).
If you do so, the value in $_GET['buttonname'] will be its value (not its id), i.e. Accept or Reject. This becomes pretty messy as soon as you get into i18n, so you might want to use different names for the buttons and then check isset($_GET['buttonname1']) and isset($_GET['buttonname2'])
Here is a code example for what you are trying to achive:
VIEW:
<?php
echo CHtml::beginForm('mycontrollerName/AcceptUserRegistration','get');
?>
<?php echo CHtml::submitButton('Accept', array('id' => 'accept', 'name' => 'accept')); ?>
<? echo ' '; ?>
<?php echo CHtml::submitButton('Reject', array('id' => 'reject', 'name' => 'reject')); ?>
<?php echo CHtml::endForm(); ?>
Note: I added the name parameter. As name is not displayed to the user, you can use accept instead of Accept.
CONTROLLER:
public function actionAcceptUserRegistration() {
if(isset($_GET['accept'])) {
//accepted
} else if(isset($_GET['reject'])) {
//rejected
}
//I recommend using POST method instead of GET for posting the form.
}