I have a form with two input text fields:
<input id="ModelName_test_0" name="ModelName[test][0]" type="text">
<input id="ModelName_test_1" name="ModelName[test][1]" type="text">
These input fields get generated with the following commands:
<?php echo $form->textField($model,'test[0]'); ?>
<?php echo $form->textField($model,'test[1]'); ?>
Now, when I submit the form I see the values in the POST request. However, when the form submit fails then I can not get the values back into the input fields. Printing the model it shows that there are no values for $test; - is this because $test is an array in the form?
Even after the validation all values are still assigned to the variables:
if($model->validate()) {
echo "<pre>";
print_r($_POST);
return;
}
This returns:
[ModelName] => Array
(
[test] => Array
(
[0] => myFirstInputField
[1] => mySecondInputField
)
)
So the values are in the POST but after the failed validation they are gone and I get empty variables:
[ModelName] => Array
(
[test] =>
)
The variable test is declared safe in the validation rules.
What I want to achieve is:
If the validation fails put the entered values back into the appropriate input text fields.
Any pointers in the right direction would be helpful :)
The problem is, that CHtml::activeTextField expects a model and one of its attributes as parameters. If the attribute is named test then have $form->textField($model,'test');. After your form is submitted, either test doesn't have any values or it is an array (check this to confirm, either echoing it's value or doing a print_r on $model->attributes).
I found this article on the yiiframework.com website which helped me solving this issue: http://www.yiiframework.com/doc/guide/1.1/en/form.table
This is the sample code which you would put it your controller:
public function actionBatchUpdate()
{
// retrieve items to be updated in a batch mode
// assuming each item is of model class 'Item'
$items=$this->getItemsToUpdate();
if(isset($_POST['Item']))
{
$valid=true;
foreach($items as $i=>$item)
{
if(isset($_POST['Item'][$i]))
$item->attributes=$_POST['Item'][$i];
$valid=$item->validate() && $valid;
}
if($valid) // all items are valid
// ...do something here
}
// displays the view to collect tabular input
$this->render('batchUpdate',array('items'=>$items));
}
And this is what the view would look like:
<div class="form">
<?php echo CHtml::beginForm(); ?>
<table>
<tr><th>Name</th><th>Price</th><th>Count</th><th>Description</th></tr>
<?php foreach($items as $i=>$item): ?>
<tr>
<td><?php echo CHtml::activeTextField($item,"[$i]name"); ?></td>
<td><?php echo CHtml::activeTextField($item,"[$i]price"); ?></td>
<td><?php echo CHtml::activeTextField($item,"[$i]count"); ?></td>
<td><?php echo CHtml::activeTextArea($item,"[$i]description"); ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php echo CHtml::submitButton('Save'); ?>
<?php echo CHtml::endForm(); ?>
</div><!-- form -->
Both code snippets are taken from yiiframework.com where you can find more details on how to use 'Tabular Inputs': http://www.yiiframework.com/doc/guide/1.1/en/form.table
Related
I'm trying to pass data I've retrieved from my SQL Database to a $_SESSION array for a shopping cart to be displayed to the user. I don't think the information is actually getting passed over, the program ends up displaying but it gives me blank fields. For reference, I'm trying to pass over data through multiple PHP files. Additionally, once I pass the information over, I'm unsure how I would loop said $_SESSION array the user to add multiple items.
I'm not sure if the issue is through my include() with my index, or maybe my form action in the product_list. But somewhere either the data isn't passing or it doesn't work the way I think it does.
This is the code within my product_list where the data is initially sent
foreach ($products as $product) : ?>
<tr>
<td><?php echo $product['productID']; ?></td>
<td><?php echo $product['productName']; ?></td>
<td class="right"><?php echo $product['price']; ?></td>
<td><form action="../Cart/index.php" method="post">
<input type="hidden" name="action"
value="add_product">
<input type="hidden" name="product_name"
value="<?php echo $product['productName'];?>">
<input type="hidden" name="product_price"
value ="<?php echo $product['price'];?>">
<input type="submit" value="Add to Cart">
<?php endforeach;
This is the code within my index where the the shopping cart is included
if ($action == 'add_product')
{
include('../Cart/index.php');
}
This is my code within the ```index within the shopping cart path
$action = 'add_to_cart';
if(!isset($_SESSION['cart']))
{
$_SESSION['cart'] = array();
}
if($action == 'add_to_cart')
{
$cart_product_name = filter_input(INPUT_GET, 'product_name');
$cart_product_price = filter_input(INPUT_GET, 'product_price', FILTER_VALIDATE_FLOAT);
$product = array('price' => $cart_product_price, 'name' => $cart_product_name);
$_SESSION['cart'][] = $product;
include('cart_view.php');
}
And this is where the $_SESSION array should be displaying
<main>
<h1>Your Cart</h1>
<link rel='stylesheet' type="text/css" href="main.css">
<?php
print_r($_SESSION['cart'][0]);
?>
What's actually being displayed is this Array ( [price] => [name] => )
The first problem I see is that your input names are incorrect. Every product name input is currently name="product_name", likewise for product_price. You need to pass these through as an array, or each with their own unique key. Otherwise you get one single post value for product_name and product_price - which will be whatever the last inputs with those names are in the form.
You can pass them as an array by doing name="product_name[]" and then your post will contain an array of all those values, in the order that they appear in the form.
Next, you say your output is currently Array ( [price] => [name] => ). This indicates to me that your session is in fact working, because you have keys in that array. So actually setting the session is not the problem. So then you go back to where the session is being set, and see that you are using INPUT_GET in your filter_input parameters - but you are receiving POST values. Your parameter should not be INPUT_GET, it should be INPUT_POST.
Once you get all that cleared up you're still going to have a problem, because the inputs for product_name and product_price are going to be arrays with multiple values. You need to loop through them to assemble the final array that gets set to the session. I'll leave that to you to explore, because that will look far different than what you currently have going on in your add_to_cart action.
I'm not sure if what I'm asking for is possible, but here's the scenario:
I have a foreach() loop that returns some values in HTML format:
<?php foreach($stuff as $s) { ?>
<tr>
<td><?php echo $s['Model']['data']; ?> </td>
</tr>
<?php } ?>
What I need to do is put a checkbox next to each $s['Model']['data'], preferably with $s['Model']['data'] as the label, and be able to set a value in a table based on whether the box is checked. So, my edit.ctp would look like this:
<?php foreach($stuff as $s) { ?>
<tr>
<td><?php echo $this->Form->input('flag', array('type'=>'checkbox, 'default'=>'', label=>' $s['Model']['data']', 'value'=>1 )); ?> </td>
</tr>
<?php } ?>
I have no trouble displaying the above. My problem is that I don't know how to tell my controller to update the necessary field if the labeled box is checked. Here's my first run at it:
if($this->request->save($this->request->data)) {
foreach($stuff as $s) {
$this->Model->id = $s['Model']['id'];
if(isset($this->request->data['FormName']['flag'])) {
$this->Model->set('flag', 1);
$this->Model->save('flag', true);
}
}
}
No errors at runtime, but nothing happens. The flag field in the Model I need to update remains = 0. I can debug $stuff and see data, so I know it's there. I also know that my edit function is hitting the foreach() loop. What might I be missing? Do I need to assign the checkbox a different value or check for whether it's set some other way?
It seems like you need to identify each checkbox to the current item by modifying the name of each checkbox, otherwise it will just use the value of the last checkbox for all the items.
<?php foreach($stuff as $i => $s) { ?>
<tr>
<td><?php echo $this->Form->input('flag'.$i, array('type'=>'checkbox, 'default'=>'', label=>' $s['Model']['data']', 'value'=>1 )); ?> </td>
</tr>
<?php } ?>
Then in the controller look for that specific flag
if($this->request->save($this->request->data)) {
foreach($stuff as $i => $s) {
$this->Model->id = $s['Model']['id'];
if(isset($this->request->data['FormName']['flag'.$i])) {
$this->Model->set('flag', 1);
$this->Model->save('flag', true);
}
}
}
Which assumes that ht elements in $stuff are always in the same order.
I have a site based on wordpress. I need to allow people to create posts from frontend so I have made a multi-part form which works pretty well. There are three parts of the form and each part of the form is validated before moving to the next part. Data is passed to another page through hidden inputs.
My form template looks somewhat like this ( complete code is pretty massive and irrelevant here, so just showing just the relevant parts ) which I hope is enough to give an idea how the form works.
MULTI-PART FORM WP-TEMPLATE SAMPLE CODE :
<?php
global $wpdb;
$this_page = $_SERVER['REQUEST_URI'];
$page = $_POST['page'];
if ( $page == NULL ) { ?>
<?php include_once('multiparts/form-files/first_part.php'); ?>
<?php } else if ( $page == 1 ) { ?>
<?php include_once('multiparts/validation/validate_first_part.php');
if (isset($_POST['submit-1']) && (!empty($error))) { ?>
<div class="error-head">Cannot continue registration. Error/s highlighted below.</div><br/>
<?php echo $error . '</br>'; ?>
<?php } else {
include_once('multiparts/form-files/second_part.php');
}
?>
<?php
} else if ( $page == 2 ) { ?>
//SO ON AND SO FORTH
<?php
}
?>
Recently, I have a added several checkbox fields in the form with an intention to display values of selected checkboxes, in the created posts. So here is a relevant html form code that I am currently using.
<fieldset class="work-areas">
<label for="areas" class="label">INTERESTED IN :</label></br>
<div class="work-class">
<input type="checkbox" name="workareas[]" value="administration"/>administration</br>
<input type="checkbox" name="workareas[]" value="technical"/>technical</br>
<input type="checkbox" name="workareas[]" value="creative"/>creative</br>
<input type="checkbox" name="workareas[]" value="fieldwork"/>fieldwork</br>
<input type="checkbox" name="workareas[]" value="marketing"/>marketing</br>
</div>
</fieldset>
I insert the values of these checkboxes into the post just like any other custom fields using this code: add_post_meta($pid, 'areas', $workareas, true );. In the processing part it is assigned a meta_key areas. I display it in the single.php with the code below :
<?php $areas = get_post_meta($post->ID, 'areas', true); ?>
<?php if (is_array($areas)) : ?>
<h4>INTERESTED AREAS OF WORK:</h4>
<?php if (is_array($areas)) {
foreach($areas as $area) {
echo '<li>'.$area.'</li>';
}
}
?>
<?php endif;?>
ISSUE: All this works well when the above given html form code for checkboxes is in the last/third part of the form. But it does work when the same checkbox fields is in the second part of the form. I guess it simply does not pass the array values of the selected checkboxes to the third part. Print_r shows an empty array and obviously does not display anything in the single.php too. Although I understand that the trouble is just the array of selected checkbox values, NOT being carried to the third part properly, I need help as I am noob to all this.
So the bottomline question is how do I save the array of the selected
checkboxes' values in the second part and carry it to the third part
and finally assign it to a variable which will hold the array values.
That which can be displayed in post using the code above.
THINGS TRIED : I have looked into this thread here and I am confused where I will insert my checkbox fields and not even sure it applies to my situation. I have been able to pass other text input values from one part to another part of the from using something like this :
<input type="hidden" name="eligible" value="<?php echo $eligible;?>" />
So, I tried using name="workareas[]" but did not work. I am doing print_r() for everything I am trying and till now have only been getting empty array. I am still going through tons of other threads looking for possible hints. In the meanwhile if you can help, that will be great. Thanks in advance.
UPDATE : Solved, please check the answer.
Not a WP user but your checkboxes are named "workareas" but you seem to refer to them as "areas" everywhere else.
Thanks for the suggestions in the comments but I have found a graceful and robust solution in my opinion, that is using sessions. I followed the basic idea from here which actually deals with a multipart form with sessions. Now I have the following code in my third/last part of the form, at the very beginning of the document. At this time please remember that the html checkbox fields as illustrated above in the question are in the second part.
<?php
session_start();
$_SESSION['workareas'] = $_POST['workareas'];
$result=$_POST['workareas'];
?>
The code is that is repeated during the validation of the third part is the same but this way the variable $result is still holding the values of the array of the selected checkboxes from the second part of the form.
session_start();
$result=$_SESSION['workareas'];
You can do a print_r($result) at this point and check. Furthermore, if you want to insert these array values to post in order for them to show up in the post just assign meta_key eg. areas to $result and use the code below to add it as a custom field :
add_post_meta($pid, 'areas', $result, true);
In the single.php you can use the code below to pull values from the array and show. Do not avoid if(is_array) statement else wordpress might throw an error warning: invalid arguments supplied foreach(). Goodluck.
<?php $areas = get_post_meta($post->ID, 'areas', true); ?>
<?php if (is_array($areas)) : ?>
<h4>INTERESTED AREAS OF WORK:</h4>
<?php if (is_array($areas)) {
foreach($areas as $area) {
echo '<li>'.$area.'</li>';
}
}
?>
<?php endif;?>
In consequence from yesterdays post as i was trying to transfer some variables between the controller and the view today I am trying to get data from a form and update the db but am having trouble getting those values.
this is function from the controller which is called from the form of the view
function updateRecords(){
$data2=array('name'=>$this->input->post('first_name'),
'surname'=>$this->input->post('last_name'),
'contact'=>$this->input->post('contact'),
'email'=>$this->input->post('email_address'));
print_r($data2);
}
when I try to print the data2 array I get: Array ( [name] => [surname] => [contact] => [email] => )
this is the code from the view:
<fieldset style="text-align:left">
<legend><h2>Edit Clients Details</h2></legend>
<?php
$this->load->helper('form');
echo form_open('site/updateRecords');
echo form_input('first_name', $records['0']->name);
echo form_input('last_name', $records['0']->surname);
echo form_input('contact', $records['0']->contact);
echo form_input('email_address', $records['0']->email);
echo validation_errors('<p class="error">');
echo anchor('site/updateRecords','Save');
echo form_close();
?>
</fieldset>
<p>
<?php echo anchor('site/add','Add clients');?>
<?php echo anchor('site/members_area','Go Home')?>
<?php echo anchor('login/logout', 'Logout'); ?>
instead of
echo anchor('site/updateRecords','Save');
try use
echo form_submit('mysubmitname', 'Save!');
anchor can't submit form data by default. If you use ajax, create javascript function which serialize form data and post to the server.
i hope this help
There are a couple of ways to have the id be accessible. One is to structure the edit page call so that it has the id in it. Normally I do this by setting up my urls to be something like: http://site.com/client/client_id/edit for the edit page. Alternately, you can stash the record's id in a hidden form field when you call the form up and then pass it back as part of the post.
I'm trying to make update form, that is going to retrieve the data for the specific ID selected, and fill in the form, so its going to be available for updating.
When I click edit on the specific entry (Product in my case), it takes me to the edit_product_view, but states the error "Trying to get property of non-object" for every variable that I use in set_values of the form elements.
Using print_r, I get the correct associative array, so it's passed correctly.
This is excerpt of my edit_product_view.
<h2><?php echo $heading; ?></h2>
<hr>
<table id="newproduct">
<?php echo form_open('products/edit/'.$product->id); ?>
<tr>
<td class="label"><?php echo form_label('Name:');?></td>
<td><?php echo form_input('prodname', set_value('prodname', $product->prodname));?></td>
</tr>
<tr>
<td class="label"><?php echo form_label('Product Type:');?></td>
<td><?php echo form_dropdown('ptname_fk', $product_types, set_value('ptname_fk', $product->ptname_fk));?></td>
</tr>
$product is the array holding all the key-value pairs, but I cannot fill the form for some reason.
Thank you in advance!
To access the elements in the array, use array notation: $product['prodname']
$product->prodname is object notation, which can only be used to access object attributes and methods.
To get the value:
$query = $this->db->query("YOUR QUERY");
Then, for single row from(in controller):
$query1 = $query->row();
$data['product'] = $query1;
In view, you can use your own code (above code)
In my case, I was looping through a series of objects from an XML file, but some of the instances apparently were not objects which was causing the error. Checking if the object was empty before processing it fixed the problem.
In other words, without checking if the object was empty, the script would error out on any empty object with the error as given below.
Trying to get property of non-object
For Example:
if (!empty($this->xml_data->thing1->thing2))
{
foreach ($this->xml_data->thing1->thing2 as $thing)
{
}
}