PHP (Yii) Passing variable to controlle via form - php

I have a variable in my view $models which I want to pass to my controller for a function which I'm calling using a submit button.
<?php echo CHtml::beginForm('', 'post');?>
<fieldset>
<?php echo CHtml::submitButton('Confirm', array('name'=>'confirm', 'class'=>'btn btn-danger')); ?>
</fieldset>
<?php echo CHtml::endForm(); ?>
how do I access the $models variable from the function in the controller.
I'm not entirely sure how this works and I would have thought I could just use $_POST['models'] but it's saying it's an undefined variable (although I can var_dump on the page and it's definitely not) so I think i'm just trying to access it incorrectly or not submitting it correctly.

This is a html form submission and php syntax problem, but not yii-specific.
Whatever framework you use, even in plain static html, the basic idea of form submission is the same: if you want to send data to a page with a form, you need to put that data in your form, either as a form input the end-user can enter or select (text inputs, dragdown boxes, radios and checkboxes), or as a hidden input. Page2 doesn't care if $models was set on Page1. You need to send the data to Page2.
In PHP, you can't display an array with echo $arrayVar.
For your specific problem, I assume $models is an array of models. Do NOT pass the whole models' definition in your form, just pass their primary key ids. On your next action, just fetch back those models with YourMode::model()->findByPk(). I think you could do this two ways:
<?php
// Idea 1 (untested code)
// Convert an array of ids to a string
$tmp = array();
foreach($models as $model){
$tmp[] = $model->yourPrimaryKey;
}
echo '<input type="hidden" name="whateveryourparamis" value="'.CHtml::encode( implode('|',$tmp)).'">';
// $whateveryourparamis will be a string like: "47|388|638|877". Use explode() to convert it to an array
// Your could also use json_encode/json_decode instead of implode/explode
// Idea 2 (untested code)
// Pass an array of ids (yeah, this is possible)
foreach($models as $model){
echo '<input type="hidden" name="whateveryourparamis[]" value="'.CHtml::encode($model->yourPrimaryKey).'">';
}
// $whateveryourparamis will be an array like: array(47, 388, 638, 877)
?>

I suppose this ain't the best way to achieve what you want, but you can always access the controller through:
$controller = Yii::app()->controller;
And then do with it whatever you want, for storing a variable in your controller, you probably will have to add a variable to your class.
Another variant would be to use CStatePersister http://www.yiiframework.com/doc/api/1.1/CStatePersister or you could also directly write in to $_SESSION..
From what you write, I suppose you should use Sessions for storing that data.

Related

Form reviewing in HTML

I hope I'm not posting a duplicate question but I've looked around (and googled as well!) and nothing has given me the answer I'm looking for.
I have a form in HTML. When the user submits the form the values get stored with mysql under their user account for the site.
The issue is, I'd like the user to be able to go back and edit the form any time they like.
I could certainly just populate the form with values from php when the users review the form, but it gets tricky when I try to populate a file input field (and the file has been saved in mysql using the blob type). Not to mention that I'd like to do this as cleanly as possible.
Ideally it would be nice if there was a convenient module for reviewing forms that have already been submitted in JQuery per se.
Can anyone offer any advice? Thanks in advance!
Edit:
Here's a good example of what I mean - in chrome if I fill out a form and redirect to the next page after hitting submit, if I hit back I come back to the form and it's still filled out with the information I entered previously! Could I invoke this behaviour whenever I want to, as opposed to only when the user hits back?
You can't pre-fil an <input type="file" . . but surely when they come back to the form, they want to see the file they've uploaded .. this is what you mean right ..
So if its a picture, you could just do: <img src="loadpic.php?id=$var" />
If it's files they've uploaded, just list the file name / date and other data.. etc in some sort of list.
Then you could still show the <input type="file"> .. but with the label, 'add more pictures' or 'add another file'. .etc
Unless someone has a better way, at the moment I'm using a combination of 2 things:
1) Utilizing the $_SESSION variable
2) Setting the "name" attribute of every input in the form to the name of the field it corresponds to in the database.
This way I can loop through all the values dynamically instead of hardcoding them all in. Some input types (like file) are exceptional and will be handled on their own. Other that I can do something like this:
To insert into mysql:
$fields = array();
$values = array();
foreach ($_POST as $field => $value) {
$fields[] = $field;
$values[] = addslashes($value);
}
$fieldString = 'Table_Name('.implode(', ', $aFields).')';
$valueString = "VALUES('".implode("', '", $aValues)."')";
mysql_query("INSERT INTO $fieldString $valueString");
Reviewing the form is somewhat similar. I am using javascript to hook into document.onload. I need to pass javascript the records from mysql so that it may populate the form. Then it's a simple matter of getting elements by their name and assigning them their values that were passed from php.
The easiest way to do it and not have to go back to the database would be to store the values in a session.
<?php $_SESSION['myvalue'] = $inputvalue; ?>
On the html form use:
<input type="text" name="myName" value="<?php echo $_SESSION['inputvalue']; ?>" />
When completed don't forget to unset the session variable:
<?php session_start(); unset($_SESSION['myvalue']); ?>

PHP going back and keeping arguments

I have used this page http://www.binarytides.com/blog/php-redirect-go-back-to-previous-page/
to go back
but from
http://page.co/test.php?item=26
I post something to post.php and then call the php Go back function but I go back to
http://page.co/test.php
losing the argument path, any idea?
In Your form fill in the query string to the action attribute, like this:
<form action="?item=26" name="myform">
...
</form>
and after the submission Your HTTP_REFERER will contain this query string so redirect to it will be successfull...
EDIT: If the form is on the page post.php, it is enough to use action="?item=26" - of course You can and should use PHP to write down the number/ID of item from whenever it may come...
Lets say Your item ID is stored in the variable $item_id - then Your action will look like this: action="?item=<?php echo $item_id; ?>".
You should use sessions for stuff like this. Set a session when posting the data and you're set.

How to get selected index of dropdown from PHP post

I have an HTML form which contains a drop down, a tinyMCE textarea, and a save button.
The dropdown is used to select a file to edit.
I load up the required file into the tinyMCE editor by making an ajax call when the jquery change() event is triggered from the dropdown. That works fine.
The problem I'm having is saving the file off. I am trying to do it by posting the form off to another php page which will write to the file and then send us back to the main page.
This is the php code within my writeFile.php page:
<?php
session_start();
if (!isset($_SESSION['id'])) {
header ('Location: index.php?error=0');
}
else {
if (isset($_POST['save'])) {
$text = $_POST['mceContent'];
$index = $_POST['files']; // << PROBLEM LINE!
$array = array('homeText.txt', 'anotherText.txt');
$fileName = $array[$index];
$path = '../txt/'.$fileName;
$length = strlen($text);
echo "INDEX: $index"; // TO TEST THE INDEX VARIABLE.
$fh = fopen($text,'w',true);
fwrite($fh,$text,$length) or die('Could not write');
fclose($fh);
header ('Location: admin.php');
}
}
?>
The $index variable is meant to be the selected index in the dropdown, however it is posted by my form as the selected string value in the dropdown.
I can think of three solutions (ordered from least likely to work to most likely)
There is some way to get the index from that php post?
I can make a change in the HTML form/select tag to tell it to post the index and not the value string
I change it to a jquery event, with the on-click, and pass in the index to a post manually with xhr.
If someone could help me with implementing one of these method that would be great.
If you have your own, better solution I would be happy to hear that as well.
Also note that I can't build the path from the value string, because my dropdown uses descriptive strings, not actual file names.
Thanks in advance, bear in mind I'm new to php and especially jquery.
I am not sure why you can't use the value attribute - the descriptive string would be the text portion of the option element, the filename to save could be the value:
<option value="path/to/file_to_save.php">Descriptive file name</option>
Doing it that way, the user sees the descriptive text, the server gets a useful bit of information it needs when the form posts.
If that is not an option, you could add an onSubmit event to the form in which you pass the selectedIndex property to a hidden form field, then return true and let the form submit normally.
Form snippet
<form onsubmit="return beforeSubmit()">
<input type="hidden" name="file_index" value="" id="file_index_fld" />
<select id="file_name_dropdown">
<option>...</option>
Javascript snippet
var beforeSubmit = function () {
$('#file_index_fld').val($('#file_name_dropdown').attr("selectedIndex"));
return true;
}
... now in PHP's $_POST variable, you'll see $_POST['file_index'] contains the selectedIndex of the select element.
The long and short of it is that the selectedIndex property is a DOM item and not part of the POST data. No matter what, you are either going to have to intervene with javascript to add the data to POST, or modify your option elements to pass the desired data. I would always lean toward the former route as it is less complex.
Another option I can think of: Before posting, catch the new index in the change-event and write it to a hidden input-field of your form. After that, you can serialize and post it with jQuery.

How do I pass a variable in URL using PHP?

I have a variable called $tags, which just references from a database field. When the user clicks a link with the given $tags output in it, I want that data to be stored in a variable on the target page.
For instance, the user is on a todolist.php, that contains several tasks. They can see the parts associated with this task by clicking a link that goes to a partslist.php page. In the link, I need to contains the $tags data, so javascript on the partslist.php page knows what part to highlight.
So I need to know 1) how do I output $tags in the link of todolist.php, and 2) how do I receive that output and store it on a variable on the partslist.php page?
I have done similar POST and GET commands, but I can't quite figure this out.
partslist.php?tags=<?php echo urlencode($tags) ?> .. is this what you are asking ? Or there are multiple tags ? Please give examples / code blocks / links
On the partslists side you can do this :
$tags = $_GET['tags']; // You don't need urldecode here, because $_GET is a supergobal and it is already decoded.
You pass URLs to pages in one of two ways: $_GET or $_POST. $_POST requires that you have a form setup like:
<form method="post" action="page.php">
<input type="text" name="myvariable" value="test">
<input type="submit">
</form>
And $_GET requires that you link to the page like:
click me
In the first scenario, when the user hits submit, page.php will have access to the variables submitted from the $_POST array. In this case, $_POST['myvariable'] will equal "test";
In the second, $_GET['myvariable'] will equal test.
is $tags an array?
If so you can output the $tags array in the following format
partslist.php?tags[]=tag1&tags[]=tag2&tags[]=tag3
if you would then output the $_GET global in the partslist.php script you would end up with an array like this:
Array
(
[tags] => Array
(
[0] => "tag1"
[1] => "tag2"
[2] => "tag3"
)
)
If the URL for the link they click on contains URL parameters, those will be available on the target page. For instance,
// Generate a link like this with PHP
<a href="somepage.php?name=bob&weight=150">
// On somepage.php
$name = $_GET['name'];
$weight = $_GET['weight'];
Note: for security, you may want to encrypt this data before putting it in the link, and decrypt it on the other end.
For the part where you hand some data to Javascript, you can interpolate PHP in your Javascript the same as your HTML. So, you could say:
//JS
var foo = <?PHP echo $foo ?>;
Alternately, you could store data in an HTML element:
<div id="foo" data="<?PHP echo $data ?>">
... and then grab that using Javascript.

How can I stop PHP from replacing the variable everytime the form is updated?

Basic question - I have a text area with a submit button that is linked to the variable $ListItem.
Further down the page I want to print $ListItem in a <li> and everytime something new is entered in the text area, I want to assign it a new variable ($ListItem2 perhaps?) and then print it below the previous one.
With my current code, every time a new string is entered in the text area, it replaces the existing variable:
<?php
$ListItem = $_POST["ListItem"];
?>
<form method="post" action="<?php echo $PHP_SELF;?>">
<textarea name="ListItem" cols=80 rows=6></textarea> <br />
<input type="submit" value="Submit"> <br />
</form>
<li><?php echo $ListItem; ?></li>
Am I going to have to use a database?
You could pop it onto an array stored in the session:
$_SESSION["vars"][] = $_POST["ListItem"];
This would keep the full history through future submits. Printing them would be as simple as cycling through the session array:
foreach ($_SESSION["vars"] as $var) {
echo "<p>{$var}</p>";
}
Remember to start the session before anything else takes place:
session_start();
Detailed Explanation (requested in comments)
The first item in my answer was an example of appending another item onto an array. If we start with an empty array:
$myArr = array();
We can add new entries with the following syntax:
$myArr[] = "Foo";
$myArr[] = "Bar";
Our array now has two items within it. This would be the same as doing this:
$myArr = array("Foo", "Bar");
Using the double-bracket method is a quick way to place more items into the array, while keeping what is presently there to begin with. There are other ways to do this, for instance you could use the array_push() function:
array_push($myArr, "Foo");
This does the same thing as our previous example though, so it doesn't offer much of a difference. Stepping back now, we note that our array is stored within the SESSION array. This is an array that is useful for storing data that will be used frequently during a users visit to your website. It's often times a better alternative to storing trivial data in a database, and making calls upon each request.
Again, we have an array:
$_SESSION["vars"] = array();
Basically all we're doing is setting an array within an array, handled by the key "vars". The key is important so we can quickly reference this data at a later time. And back to our first line of code, you can now make more sense of what we were doing:
$_SESSION["vars"][] = $_POST["ListItem"];
So all this is doing is adding the new value of $_POST["ListItem"] onto the array stored within $_SESSION["vars"] where it can later be retrieved.
Global Session Array
I would append the text area data to a global session array.
Eventually you will want to use a database.

Categories