Retrieving field data from Ninja Form - php

I have a wordpress website with a ninja form. In the confirmation page I would like to be able to use the values submitted in the ninja form by my users as PHP variables.
Any thoughts on how I should do this?
Let's say I use radiobuttons to ask someone if they are male or female. How do I echo the given value on the confirmation page?

Ideally you should:
1) Create a new custom plugin (this way you will be able to update your Ninja Forms plugin, theme and still have you changes intact and easily transferable to other WordPress site).
2) Register a Ninja Forms Action:
public function register_actions( $actions ) {
$actions['newsuccessmsg'] = new NF_XXX_Actions_NewSuccessMsg();
return $actions;
}
add_filter( 'ninja_forms_register_actions', 'register_actions' );
3) Add an action class:
final class NF_XXX_Actions_NewSuccessMsg extends NF_Abstracts_Action
{
protected $_name = 'newsuccessmsg';
protected $_tags = array();
protected $_timing = 'late';
protected $_priority = 10;
public function __construct()
{
parent::__construct();
}
public function save( $action_settings )
{
}
public function process( $action_settings, $form_id, $data )
{
return $data;
}
}
4) Method process will include action settings, form id and submission data. I personally just dump all details to file to see data format like this:
$f = fopen( ABSPATH . 'log.txt', 'a+' );
fwrite( $f, print_r( $data, true ) . "\n");
fclose($f);
Code snippet above will create a file log.txt in your WordPress root directory.
PS: I would recommend to refer to ninja-forms/includes/Actions/SuccessMessage.php and use it as example.

You can "POST" the form data and access them by using their name attribute value
index.php
<form method = "post" action = "postValues.php">
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female
<input type="submit" value="Submit"
</form>
postValues.php
<?php
/* Using the name attribute value to access the selected radio button
This should assign either male or female to the variable. */
$selectedGender = $_POST["gender"];
echo "$selectedGender";
?>
Note: The name attribute value for both the radio buttons should be same (It's like grouping together)

Related

How to direct to a form page based on category chosen from drop down in codeigniter?

So I try to create a page for category with dropdown, but I can't direct it to the function for each category that I've chosen and load the form view.
This is the view for choosing the category first
<select name="jenisberkas" id="jenisberkas" onchange="this.form.submit()">
<option value="roya">Roya</option>
<option value="peralihan">Peralihan</option>
<option value="validasi">Validasi</option>
</select>
<button type="submit">Submit</button>
And this is my controller look like,
function __construct()
{
parent::__construct();
$this->load->helper('url')
}
public function get_jenisberkas()
{
if(isset($_POST) && !empty($_POST())
{
if($jenisberkas = $this->input->post('jenisberkas')=='roya'; {
$data['jenisberkas'] = $jenisberkas;
$this->load->view('roya_v',$data); //directing to the form view for this category
}
elseif ($jenisberkas = $this->input->post('jenisberkas')=='peralihan';
{
$data['jenisberkas'] = $jenisberkas;
$this->load->view('peralihan_v',$data); //directing to the form view for this category
{
What I want is when an option is clicked and submitted, it will go directly to specific page form that I made for each options, while passing the value to the page.
I know there's something wrong with my controller and I think I don't need a model since this form doesn't involve a database.
Following is the code fixed:
public function get_jenisberkas()
{
if(isset($_POST) && !empty($_POST)) // Removed () from here, added )
{
if($this->input->post('jenisberkas') == 'roya') {
$data['jenisberkas'] = $jenisberkas; // Fix it yourself
$this->load->view('roya_v',$data);
}
elseif ($this->input->post('jenisberkas')=='peralihan')
{
$data['jenisberkas'] = $jenisberkas; // Fix it yourself
$this->load->view('peralihan_v',$data);)
{
I would recommend to use an Intelligent Code Editor like
https://www.eclipse.org/kepler/
UPDATE:
Well, after more than an hour thinking about it, i solved it myself (lmao) with a simple code in my form category view. And after i clicked the submit button, it will go to the specific function made for each category (yay!), that's what i actually want.
so i'm gonna put it here just incase some people out there maybe need solution for this silly case.
this is the view
if (isset($_GET["jenisberkas"])) {
redirect('mulaiberkas/' . $_GET["jenisberkas"] . "");
exit();
}
?>
<form method="get" action="">
<select name="jenisberkas" id="jenisberkas" onchange="this.form.submit()">
<option value="roya">Roya</option>
<option value="peralihan">Peralihan</option>
</select>
<button type="submit">Submit</button>
</form>
and the controller is simply contains function named as the value chosen
function __construct()
{
parent::__construct();
$this->load->helper('url');
}
function roya()
{
$jenisberkas = $this->input->get('jenisberkas');
$data['jenisberkas'] = $jenisberkas;
$this->load->view('roya_v', $data);
}
function peralihan()
{
$jenisberkas = $this->input->get('jenisberkas');
$data['jenisberkas'] = $jenisberkas;
$this->load->view('peralihan_v', $data);
}
}

Why does CI create a new row instead of updating?

I'm creating a UI in my application which will allow the user to decide the state of received content, this includes updating it. How does CI handle this?
I've tried the different update methods provided in the query builder part of the documentation, including replace and update, I pass on the data from the view to the controller, to the model in the form of an array. Yet still, when I try it, it creates a new row with that single value and with all other columns empty.
view.php
<form action="Application/Update" method="get">
<input type="hidden" name="mar-id" value="<?php echo $row['id']; ?>">
<input type="hidden" name="mar-read" value="New-value">
<?php echo anchor('http://localhost/dir/dir/dir/index.php/Application/Update', 'update'); ?>
</form>
controller.php
public function Update() {
$this->load->helper('url');
$this->load->model('Main');
$id = $this->input->post('mar-id');
$value = $this->input->post('mar-read');
$mar = $this->Main->Update($id, $value);
if ($mar == TRUE) {
redirect('http://localhost/dir/dir/dir/index.php/Application/Otherpage', 'refresh');
}
else {
redirect('http://localhost/dir/dir/dir/index.php/Application/Otherpage');
}
}
model.php
public function Update($id, $value) {
$data = array(
'status' => $value
);
$this->db->where('id', $id);
$update = $this->db->update('table', $data);
}
As I said, I expect the row to be updated based on the row-id provided. Instead it creates a completely new row with that single value. It doesn't return any error messages though.
There are a number of mistakes here.
SO to date we have established that performing var_dumps in the controller results in NULL for all your "POST" values.
I've assumed the following for simplicity.
Controller Name is: Program.php (Application is NOT an Allowed controller name as it's a foldername)
Model Name is: Mdl_update.php
View is: update_view.php
Issue #1:
Your Form has an issue where you are using an anchor tag which is just a link. It does nothing in submitting any data from the form.
So we have to remove the Anchor Tag and replace it with a Form Submit. You have to Submit the form to get any chance of sending the form data.
For testing your GET and POST I've added in Two different Forms.
In update_view.php
<!-- Set the Method to GET -->
<form action="program/update" method="get">
<input type="hidden" name="mar-id" value="<?php echo $row['id']; ?>">
<input type="hidden" name="mar-read" value="New-value">
<input type = "submit" name="update" value="Update with GET">
</form>
<!-- Set the Method to POST as this is what the Controller is Expecting -->
<form action="program/update" method="post">
<input type="hidden" name="mar-id" value="<?php echo $row['id']; ?>">
<input type="hidden" name="mar-read" value="New-value">
<input type = "submit" name="update" value="Update with POST">
</form>
What I used to display the Form in the controller by simply calling the program/index in the Program controller.
public function index() {
$this->load->helper('url');
$data['row'] = array('id' => 2);
$data = $this->load->view('update_view', $data, TRUE);
echo $data;
}
So your Controller is looking for POST and not GET. This can be proven by changing the controller up a bit for debugging.
public function update() {
$this->load->helper('url');
$this->load->model('mdl_update');
$id = $this->input->post('mar-id');
$value = $this->input->post('mar-read');
echo '<h2>POST Values</h2>';
var_dump($id);
var_dump($value);
// ****************************
// These are added in for debugging/Demonstration to show values for the form using the GET method.
$id_get = $this->input->get('mar-id');
$value_get = $this->input->get('mar-read');
echo '<h2>GET Values</h2>';
var_dump($id_get);
var_dump($value_get);
// ****************************
exit('Stopped for Debugging: Method '. __METHOD__.' at Line: '.__LINE__); // Added for Debug
$mar = $this->mdl_update->Update($id, $value);
if ($mar == TRUE) {
redirect(base_url('program/otherpage'), 'refresh');
} else {
redirect(base_url('program/otherpage'));
}
}
So you are looking for POST Data when your form method is set to GET. Please be aware of what you are setting. They must match.
If you want to use GET, you need to use $this->input->get()
The code above will let you test both.
So you now have a POST and GET Form and the controller is setup to demonstrate the two different types. Choose Either GET or POST!. That is up to you on which one you choose.
Issue #2: Expecting a return value from your Model when you are not returning anything.
In your Controller you have the line...
$mar = $this->mdl_update->Update($id, $value);
And in your Model you have...
public function update ($id,$value) {
$data = array(
'status' => $value
);
$this->db->where('id', $id);
$this->db->update('db_table', $data);
}
Your Model Method is not returning anything.
You should always look up what your return values are. I am expecting that your intention was to return the value of the update. Looking through the CI Code itself it appears that if things go wrong it will return FALSE (if the database debug is disabled - learnt something new)
I've added in some debug to assist in viewing what is going on here.
public function update($id, $value) {
$data = array(
'status' => $value
);
$this->db->where('id', $id);
$update_result = $this->db->update('db_table', $data);
echo $this->db->last_query(); // Added for DEBUG
return $update_result;
}
Now I cannot get your code to create new rows as you claim. It's impossible, with this code, to add new rows. So thats happening from something you haven't shown us but that is an aside and not important here.
If we alter the controller to view the model etc (I am only showing the changes ) we would change
exit('Stopped for Debugging: Method '. __METHOD__.' at Line: '.__LINE__);
$mar = $this->mdl_update->Update($id, $value);
To this
$mar = $this->mdl_update->Update($id, $value);
var_dump($mar);
exit('Stopped for Debugging: Method '. __METHOD__.' at Line: '.__LINE__);
If you run this and submit either the GET ( Results are NULL ) or POST, the update will always return TRUE. So your redirect etc needs to be looked at on how you decide on one or the other.
I think you should set your table columns to not allow them to be NULL AND add in some "Validation" in your controller.
ISSUE 3: No Form Validation
CodeIgniter has a Form Validation Class that I suggest you read. This is getting way too long to go into that here...
So as you go through this, you can add/remove debugging to test what is going on and progress it along the way as I have hopefully shown.
if anything is unclear, just ask. I'm sure I may have left something out.

PHP Concrete 5 Pass Variables to Add.php

I'm creating a new block and I want to pass a defined variable to the block instance on add.
In my controller, I have the following:
// declare the var
public $hasMap = 0;
public function add() {
$this->set('hasMap', $this->generateMapNumber());
}
The generateMapNumber() function looks like this:
public function generateMapNumber() {
return intval(mt_rand(1,time()));
}
In my add.php form I have a hidden field:
<?php $myObj = $controller; ?>
<input type="hidden" name="hasMap" value="<?php echo $myObj->hasMap?>" />
When I create a new block, hasMap is always 0 and the hidden input value is always 0 too. Any suggestions? Thank you!
--- EDIT ---
From the concrete5 documentation:
// This...
$controller->set($key, $value)
// ... takes a string $key and a mixed $value, and makes a variable of that name
// available from within a block's view, add or edit template. This is
// typically used within the add(), edit() or view() function
Calling $this->set('name', $value) in a block controller sets a variable of that name with the given value in the appropriate add/edit/view file -- you don't need to get it from within the controller object. So just call <?php echo $hasMap; ?> in your add.php file, instead of $myObj->hasMap.
It will not be the same value, because the function will give diferrent values every timy it is called.
So here's the solution. In the controller...
public $hasMap = 0;
// no need for this:
// public function add() { }
public function generateMapNumber() {
if (intval($this->hasMap)>0) {
return $this->hasMap;
} else {
return intval(mt_rand(1,time()));
}
}
And then in the add.php file...
<?php $myObj = $controller; ?>
<input type="hidden" name="hasMap" value="<?php echo $myObj->generateMapNumber()?>" />
It works perfectly. On add, a new number is generated and on edit, the existing number is drawn from the hasMap field in the db.
Thanks for all the input. Hope that helps someone else!

PHP MVC passing form values to controller and model

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.

Dropdown validation

I am having one dropdown option in the form called town. Already fetched values will be available in drop down from the databasetable townId. Now I want to check if the user doesn't select any choice from the dropdown and directly goes to the save button, then it should display "please choose your choice in dropdown" like that. The form is named university
I tried this code here:
if(Zend_Form_Element_Submit)
{
if($$townid=='')
{ alert("U Must Choose Town Name Here");
}
else
{
$submit = new Zend_Form_Element_Submit('Save');
$submit->setDecorators($this->submitDecorators)
->setAttrib('class','button slategray');
}
}
Inside models->university.php there are some actions for dropdown I didn't get exactly:
public function setOptions(array $options)
{
$methods = get_class_methods($this);
foreach ($options as $key => $value) {
$method = 'set' . ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
return $this;
}
Before I edited form->university (the save code already exits)
$submit = new Zend_Form_Element_Submit('Save');
$submit->setDecorators($this->submitDecorators)
->setAttrib('class','button slategray');
}
Thanks in advance.
To work properly with Zend Framework's forms I recommand to try this approach:
Create a form by extending the Zend_Form class
class Form_User extends Zend_Form
Which automatically give you access to a container to manage all your elements from this form and give you acces to a isValid() method which allow you to validate all your form elements at once and to a populate() method which allow you to feed data to your form for editing
In your new class (Form_User) you can define all your form properties and elements in the init() method.
public function init()
{
$this->setName('user')
->setAttrib('id', 'user');
$username = new Zend_Form_Element_Text('username');
$town = new Zend_Form_Element_Select('town');
$town->addMultioptions(array(...));
$submit = new Zend_Form_Element_Select('submit');
$this->addElements(array($username, $town, $submit));
}
Each of these elements can be customized with a label, a description, some validators, some filters, etc.
If you want to make an element mandatory you can set the Required property to true
$town->setRequired(true);
To validate your form after the submit has been cliqued, you can do it as simply as (assuming you do this in the controller) :
$form = new Form_User();
$postData = $this->getRequest()->getPost();
$form->isValid($postData);
This will check for the required fields as well as execute any validators that you have setted on these diverses elements.
It will return true if everything is ok, and false if there is an error. If you get an error a display the form again, error messages will be shown automatically beside each erroneous fields.
If you want to set options values of your form elements, when you initialize your form, you can pass a configuration array like this :
$form = new Form_User(array('townListOptions' => array(...));
The associated method setTownListOptions will be called automatically and will receive the array (or any other object) you assigned it with.
I could explain even further things about forms but as #Rohan stated in his comment, RTM
In asp.net
<asp:DropDownList ID="ddlusertype" runat="server" CssClass="dropdown" ></asp:DropDownList>
<asp:CompareValidator ID="CompareValidator2" runat="server" ControlToValidate="ddlusertype" ErrorMessage="select" Font-Size="XX-Small" Operator="NotEqual" Type="Integer" ValueToCompare="0"></asp:CompareValidator>

Categories