How might one use the url_for or link_to helpers to create a link to the same page passing along all GET parameters?
I have a search page which accepts multiple parameters as filters to hide certain results. For example, search.html?query=abc&people=1&groups=0 would search for all items containing 'abc' that aren't groups. I would therefore like a link which toggles these filters, passing the rest of the parameters unchanged to the current page. In the above example, links would be created to search.html?query=abc&people=1&groups=1 and search.html?query=abc&people=0&groups=0.
I am wondering if there is any way to specify 'this' as a route, such that if the route or page changed, the code wouldn't have to.
Moreover, how can one pass all parameters to the helper? $sf_params can be used to access all the parameters, and the 'query_string' property can be passed to the helper, but is there any method of combining the two short of creating the string manually?
GET parameters can be passed to a link_to method as an array in the third argument, or url_for in the second. This is illustrated as follows:
link_to('Text to display', 'routename', array('group' => 0, 'people' => 1), $link_attributes);
url_for('routename', array('group' => 0, 'people' => 1));
This is hidden in the source code. Here, $params is the list of GET parameters, and $options HTML attributes to add to the tag.
function link_to2($name, $routeName, $params, $options = array())
function url_for2($routeName, $params = array(), $absolute = false)
The $sf_params function can be converted to a suitable array for passing with getAll(). See the documentation here. Note that this is different from previous versions of Symfony. Also be aware you might have to call getRawValue() from within a template:
$params = $sf_params->getRawValue()->getAll();
$sf_context->getInstance()->getRouting()->getCurrentRouteName() can then be passed as $routeName to get the current route. Thanks to Tom for this
put vars in hidden form data types to pass them on
<form action="page.php" method="GET">
<input name="people" type="hidden" value="<?php echo htmlspecialchars($_GET['people'], ENT_QUOTES); ?>">
<input name="groups" type="hidden" value="<?php echo htmlspecialchars($_GET['groups'], ENT_QUOTES); ?>">
<input name="query" type="text" value="some_data">
<input name="send" type="submit" value="send">
</form>
Related
I am trying to use Magento 1.9 XmlConnect module to save the billing address function. In xml connect there is an action to do this, saveBillingAddressAction. In savebillingaddressAction method one line is trying to access an array from the POST variables like following -
$data = $this->getRequest()->getPost('billing', array());
How I can pass an array from client side to server side in POST variable so that billing param have the array with the needed data?
Magento repository - CheckoutController.php.
You can create arrays out of form elements using square brackets [].
<input type="hidden" name="billing[]" value="billing-info1">
<input type="hidden" name="billing[]" value="billing-info2">
<input type="hidden" name="billing[]" value="billing-info3">
This will return a zero based array (ie 0=>'billing-info1',1=>'billing-info2', etc).
If you'd like to use an associative array you just need to create a key:
<input type="hidden" name="billing[key0]" value="billing-info1">
<input type="hidden" name="billing[key1]" value="billing-info2">
<input type="hidden" name="billing[key2]" value="billing-info3">
Then your return will be something like:
'key0' => 'billing-info1',
'key1' => 'billing-info2',
'key2' => 'billing-info3'
I have a PHP form that need to submit a array of numbers, what we have in view:
<input type="text" id="ProductForm_sizeobj_1" name="ProductForm[sizeobj[1]]" value="13">
<input type="text" id="ProductForm_sizeobj_2" name="ProductForm[sizeobj[2]]" value="13">
<input type="text" id="ProductForm_sizeobj_3" name="ProductForm[sizeobj[3]]" value="13">
And I define in form class:
public $sizeobj = array();
public function rules() {
return array(
array('/** other attributes **/, sizeobj', 'safe')
);
}
Since "Sizeobj" is a dynamic attribute and the size will growth more then 3, therefore I use array. However after form submitted the error throw as follow:
Failed to set unsafe attribute "sizeobj[1" of "ProductForm".
I believe I might using the wrong method to setup array attribute, or wrong rule, any advice? I'm new to Yii, any help is appreciated.
Use name="ProductForm[sizeobj][1]" instead of name="ProductForm[sizeobj[1]]"
My question is whether I should use set_value() at all to re-populate a form. It might seem odd to say that, however I am creating a shared controller function and view which can be used to either add a new record or edit an existing one. It seems to make sense to do this since the functionality is so incredibly alike.
As such, if we call up an existing record to edit I do this:
$data['fields'] = $this->customer_model->get_customer($id);
If the form is submitted to save the record, or if we're adding a record for the first time, the form has the potential to reload if the user makes a mistake so I populate $data['fields'] this way instead:
$data['fields'] = array(
'company' => $this->input->post('company') ?: '',
'website' => $this->input->post('website') ?: '',
'credit_limit' => $this->input->post('credit_limit') ?: ''
);
My form element looks like this:
<input type="text" name="company" value="<?php echo set_value('company', $fields['company']); ?>" />
But I'm thinking it may as well look like this:
<input type="text" name="company" value="<?php echo escape_html($fields['company']); ?>" />
Since the form data could come from either user input (when adding or saving) or from the database (when retrieving a record to edit) I cannot rely entirely on post() or set_value() without the 2nd parameter. Furthermore, the second parameter for set_value() will always exist ($fields['company'] in this example) because it's initialized from the start, which is why I am thinking of just using it directly.
Is there a problem with this approach?
If you want to populate form fields on FALSE return of Form Validation or insert data for editing operations, I suggest you to use following helper:
Usage
<input type="text" name="last_name" value="<?=vset_value('last_name','',$rs);?>">
Explanation
$rs here is the $db data for record (if you are sending it to view). To stay at the safe side please include $this->data['rs'] = false; at your controller. If $rs is set and true, helper take results from it and display it. Otherwise it displays if the key exist in $_POST. If both don't exists, it display default value.
Helper
/**
* vayes_helper::vset_value
*
* Retains state of INPUT text after Form Validation
*
* #access public
* #param string name of INPUT tag
* #param string default value for INPUT tag
* #param mixed DB Result (array or object)
* #return string
*/
if(!function_exists('vset_value')) {
function vset_value ($name_of_input,$default_state='',$db_result_array='') {
$CI = &get_instance();
$render_state = $default_state;
if($CI->input->post()) {
$render_state = $CI->input->post($name_of_input);
} else {
if(is_object($db_result_array) && isset($db_result_array->$name_of_input)) {
$render_state = (isset($db_result_array->$name_of_input)) ? $db_result_array->$name_of_input : $default_state;
} else if($db_result_array != '' && array_key_exists($name_of_input,$db_result_array)) {
$render_state = (isset($db_result_array[$name_of_input])) ? $db_result_array[$name_of_input] : $default_state;
}
}
return $render_state;
}
}
If you like the way, let me know. I can supply for more form input type like select, checkbox, etc.
The approach is correct, as mentioned in the CodeIgniter docs. In fact, you don't need to include the second parameter in set_value.
set_value definition:
string set_value(string $field = '', string $default = '')
//$field: If there is a submitted field with this name, its value is returned.
//$default: If there is no matching submitted field, this value is returned.
Yes,You should.
set_value() is used to re-populate a form has failed validation.
There is no additional filtering on it, so it faster.
But, I prefer some times to use $this->input->post() for the secure.
I have a problem with zend form, where i need to built a form where field name are same but with different belongings. Here is the input fields that i wanted inside my form.
Currently i am getting with straight html but because of this i am missing validation.
<input type="text" name="travel_guide_tab[4][title]">
<input type="text" name="travel_guide_tab[4][description]">
<input type="text" name="travel_guide_tab[6][title]">
<input type="text" name="travel_guide_tab[6][description]">
In Zend Form the element names must be unique (in some way) or else they will overwrite. However you can continue using your html form and simply filter and validate in the controller using Zend_Filter_Input. The filter and validation classes are the same ones used by Zend_Form you just pass the data in a different way.
Simple example, partial:
public function someAction() {
//set filters and validators for Zend_Filter_Input
$filters = array(
'nameOfInput' => array('HtmlEntities', 'StripTags')
);
$validators = array(
'nameOfInput' => array('NotEmpty', 'Int')
);
//assign Input
$input = new Zend_Filter_Input($filters, $validators);//can also pass the data in constructor (optional)
$input->setData($this->getRequest()->getParams());
//check input is valid and is specifically posted as 'Delete Selected'
if ($input->isValid()) {
//do some stuff
}
Good Luck.
I've been googling most of the day trying to find an answer to this, but I've finally admitted defeat.
I'm working on a form in Zend Framework that needs to be able to handle variable data lengths. I have a form with some general fields that specify some general parameters (item name, language, etc) that are easy enough to deal with, but I've also got a subform called parameters which holds a variable number of key/value lairs that let you add generic parameters into the data. Demonstration form follows:
<form>
<input type="text" name="item_name" />
<input type="text" name="item_lang" />
<!-- etc -->
<input type="text" name="parameters[1][key]" />
<input type="text" name="parameters[1][value]" />
<input type="text" name="parameters[2][key]" />
<input type="text" name="parameters[2][value]" />
<input type="text" name="parameters[3][key]" />
<input type="text" name="parameters[3][value]" />
<input type="text" name="parameters[4][key]" />
<input type="text" name="parameters[4][value]" />
<!-- and so on -->
</form>
Note: the above is a massive simplification of the actual form. It's also manually built instead of being generated by zend_form.
The number of parameters can differ and can be handled client side with javascript, but I'm really struggling to initialize a form when populating it from pre-existing data for update.
I might have 2 parameters stored per item, I might have 20, I might have none at all. So I need the form to have 2 or 20 or no parameters inputs depending on the initial state of the data. Unfortunately the data is not available in init () because it's not in the form until you call setDefaults () on it.
This means I can't do a foreach() on the initial state of the form to generate the appropriate number of input boxes for the already-existing data.
I'm sure I must be missing something obvious, but the Zend documentation is pretty dreadful and I can't find any examples of this use case. It surely can't be so uncommon that it's not supported in zend_form. How do I go about generating the form in a state that allows for the initial state of the form to be variable?
ETA: The init() method on my form looks something like this (simplified to match the example):
public function init ()
{
parent::init ();
$this -> addElement ('text', 'item_name');
$this -> addElement ('text', 'item_lang');
$this -> addSubForm (new Zend_Form_SubForm (), 'parameters');
foreach ($phantom_data as $key => $val)
{
$params = new Zend_Form_SubForm ();
$params -> addElement ('text', 'key');
$params -> addElement ('text', 'value');
$this -> parameters -> addSubForm ($params, $key);
}
}
You can make data avaialbe to form like
My_Form extends Zend_Form
{
protected $_myCustomData;
public function __construct($options = null,$myCustomData)
{
$this->_myCustomData = $myCustomData;
parent::__construct($options); //Its important you call parent after above line or init will get call before initilizing customData
}
public function init()
{
$this->_myCustomData ; //here you are free to use your custom data
}
}