Equivalent of ASP.NET WebForms ViewState in PHP? - php

ASP.NET WebForms is outdated, but in one aspect it's far better than PHP: The ViewState. When you submit the form, controls stay. In PHP, you have to do everything all by yourself, rendering HTML.
Quickly, I come up with code that looks like this:
print('<input type="text" name="txtDate" value="' . (isset($_POST['btnSave']) ? $_POST['txtDate'] : Common::FormatDate($row['Date'])) . '" class="datepicker ' . ($dateValid ? '' : 'invalid') . '" />');
So I decided to at least create basic functions for rendering controls:
class Controls
{
public static function TextBox($name, $id, $value, $class)
{
return '<input type="text" name="' . $name . '" id="' . $id . '" value="' . htmlentities($value) . '" class="' . $class . '" />';
}
}
This makes things more comfortable, but it's just not the same as having a ViewState.
Not to mention that you have to duplicate code for both edit and create with different settings:
Create: value = whatever is in $_POST
Edit: value = If form is submitted, take whatever is in $_POST, otherwise take the value from the database/model. (ternary operator here)
This get's even harder when you show/hide popups!
All in all this is a very hard and uncomfortable way and I have absolutely no idea where to start improving it. What are your suggestions?

Related

How to solve this error 'Warning: Use of undefined constant asDollars - assumed 'asDollars' (this will throw an Error in a future version of PHP) '

I'm currently working on a project to build a website. What should I do to remove this error?
This is newer version of PHP.
if(!function_exists(asDollars)){
function asDollars($value){
return '$' .number_format((double)$value,8);
}
}
$pricetotal = asDollars("%10.2n", $pricetotal);
// Dynamic Checkout Btn Assembly
$x = $i + 1;
$pp_checkout_btn .= '<input type="hidden" name="item_name_' .
$x . '" value="' . $product_name . '">
<input type="hidden" name="amount_' . $x . '" value="' . $price . '">
<input type="hidden" name="quantity_' . $x . '" value="' .
$each_item['quantity'] . '"> ';
Error message:
Warning: Use of undefined constant asDollars - assumed 'asDollars' (this will throw an Error in a future version of PHP) in C:\xampp\htdocs\MyOnlineStore\cart.php on line 124
You need to put quotes around the string:
if (!function_exists('asDollars')) {
However, the function you're defining in this case doesn't seem to match the way you're calling it later. You call it with two arguments, a format string and a value, but your definition only takes a value.
It's not clear why you think you need to define the function here conditionally. Is there some reason you can't ensure that the library that defines asDollars is properly loaded?

jQuery Modification of Ajax Populated Form Fields

I have a form, and when a certain select box changes, it uses Ajax to populate some checkboxes. Works great.
However, when I check these checkboxes, I'd like to use jQuery to modify another part of the form - this does not seem to be working... the jQuery does not fire at all.
Is this something to do with when the jQuery loads vs the ajax request and its just impossible? Or is there likely an error somewhere in my code?
The Ajax.php page (which works just as expected)
... some other code ...
$fields = "";
$i = 0;
foreach($cols as $c){
$fields .= '<tr><td width="50%"><input class="fieldCheckBox" data-num="' . $i . '" type="checkbox" name="data[' . $_GET['t'] . '][fields][' . $i . '][field]" value="' . $c . '"> ' . $c . '</td><td width="50%"><input type="text" name="data[' . $_GET['t'] . '][fields][' . $i . '][fieldAs]" class="form-control" style="width: 150px;"></td></tr>';
$i++;
}
echo $fields;
And then my jQuery request (which isn't firing)
... document.ready function...
$(".fieldCheckBox").change(function(){
alert("were in!");
});
This is your problem:
$(".fieldCheckBox").change(function(){
The value of the checkbox is not actually changing so this will never execute.
Instead you can check for the click event for example:
$(".fieldCheckBox").click(function(){
Edit: If the checkboxes don't exist on page-load, when your javascript is executed, you need event delegation to make sure the events get registered.
A simple example:
$('body').on('click', '.fieldCheckBox', function(){

$_POST doesn't work for PHP post. ISSET reports that no such value was forwared via post method?

I have a form for a comment section. Here every comment has unique IDs.
But however, the comments aren't forwarded to the action PHP form.
Code for comments:
echo '<form action="interact.php" method="post">';
$new_refreshed_ID = 'uni_story_ID_' . $row['ID'] . '_comment_ID_' . $cache_ready_new_comment_ID;
echo '<textarea name="' . $new_refreshed_ID . 'rows="12" cols="70"></textarea>';
echo '<button type="submit">Submit</button>';
echo '</form>';
$_SESSION['assoc'] = $row['ID'];
$_SESSION['cache_comment_details'] = $new_refreshed_ID;
My code for receiving the request:
interact.php:
<?php
session_start();
$assoc = $_SESSION['assoc'];
$get_comment = $_SESSION['cache_comment_details'];
if(isset($_POST[$get_comment])) {
echo "yea!";
} else {
echo "no!";
die();
}
I get no in the interact.php which means that no data was forwarded.
How can this be?
btw comment id's are in this manner (for example):
uni_story_ID_4_comment_ID_17
I did check $new_refreshed_ID. It is showing all the values properly as desired. I did start the sessions in the both PHP files.
echo '<textarea name="' . $new_refreshed_ID . 'rows="12" cols="70"></textarea>';
You need to close the name of textarea like this:
echo '<textarea name="' . $new_refreshed_ID . '" rows="12" cols="70"></textarea>';
Edit:
Even Better to not use php when not needed (to avoid those) you can maybe do something like this:
<textarea name="<?php print $new_refreshed_ID;?>" rows="12" cols="70"></textarea>
Please note that this is an Example, i'm only printing what is really needed with php, otherwise i'll stay with html :)

render individual option from radio Element in Zend Forms

I have this element inside my Zend form
$genderOptions = array( 'male'=>'male', 'Female'=>'Female');
$gender= new Zend_Form_Element_Radio('gender');
$gender->setDecorators(array('ViewHelper'))
->setAttrib('name', 'gender')
->setAttrib('class', 'required error pull-right')
->setAttrib('id', 'gender')
->setRequired(false)
->setMultiOptions($genderOptions);
And I want to retrieve the inputs individually in the viewscript (phtml file). I've tried
as
<div>
<span>Male</span>
echo $this->myForm->gender['male'];
</div>
<div>
<span>Female</span>
echo $this->myForm->gender['female'];
</div>
how can I do that using Zend Form?
Thanks
For form elements extending Zend_Form_Element_Multi you can use the getMultiOption($option) to fetch a single option.
View.phtml
<div>
<span>Male</span>
<?php echo $this->myForm->gender->getMultiOption('male'); ?>
</div>
<div>
<span>Female</span>
<?php echo $this->myForm->gender->getMultiOption('female'); ?>
</div>
Alternatively, you may want to check that the option is available before you attempt to use it (or you will get NULL)
<?php
$gender = $this->myForm->gender;
$option = $gender->getMultiOptions(); // returns assoc array
if (isset($option['male']))
printf('<div><span>Male</span>%s</div>', $option['male']);
if (isset($option['female']))
printf('<div><span>Female</span>%s</div>', $option['female']);
?>
Edit
Having re-read your question I can see you're looking for the individual radio elements, rather than the value.
This may be harder to achieve as the Zend_Form_Element_Radio class actually represents all the radio options; Where the view helper Zend_View_Helper_FormRadio loops over each 'option' (i.e. male, female) and returns the complete HTML string with each <input type="radio"/> already included.
Shockingly the Zend_View_Helper_FormRadio helper actually has all of its HTML generation code within one method; This makes it very hard to override it without duplication.
Personally, I would :
Create a new helper MyNamespace_View_Helper_CustomFormRadio extending Zend_View_Helper_FormElement
Copy the entire contents of the Zend_View_Helper_FormRadio (FormRadio()) into your new helper
Modify section where the each radio input is created.
For example
$radio = '<div><span'
. $this->_htmlAttribs($label_attribs) . '>'
. (('prepend' == $labelPlacement) ? $opt_label : '')
. '<input type="' . $this->_inputType . '"'
. ' name="' . $name . '"'
. ' id="' . $optId . '"'
. ' value="' . $this->view->escape($opt_value) . '"'
. $checked
. $disabled
. $this->_htmlAttribs($attribs)
. $this->getClosingBracket()
. (('append' == $labelPlacement) ? $opt_label : '')
. '</span></div>';
Then you can use it within your view with $this->customFormRadio()

how can I recieve this form in cart.php

$index = 1;
foreach($product['varieties'] as $variety){
echo '<input style="width:10px; margin-left:9px; " name="price_' . $index . '" type="checkbox" value="' . $variety['price']. '" />';
echo '<input name="size_' . $index . '" type="text" value="' . $variety['size']. '" />'; $index++;
}
if you can see This will have an index=1 and it will be incrementing where each iteration will be price_1, price_2, etc.and size_1,size_2. Now with a dynamic name="" input how can I receive in the cart.php when each name will be different?
it would be something like $price= "'..',$_POST['price_']"? well I have not idea how can I receive this name index from the cart.php url.
Thnank you.
Instead of string building the name like size_1, why not make the name like this size[].
Then you can instantly access it like an array via PHP.
Look at alex's answer. It is better suited to the circumstances..
You could, at the end, add a hidden text box with the number of items (the $index value). and read it back
so after the loop add
echo '<input name="counter" type="hidden" value="' . $index. '" />'
and when you try to read it, the first thing would be to read the $POST['counter'] and then loop again from 1 to that value reading the $POST['price_'.$loop_counter]
You could find the values with something like this:
$prices = preg_grep('/^price_\d+$/', $_POST);
foreach($prices as $P) {
$idx = substr($p, 5); // extract the digits, which we know will be at position 5->end
$size = $_POST['size_' . $idx];
etc....
}
This assumes for that for every price_#, there's a corresponding size_#

Categories