How do I set the 'value' in my Zend form checkbox? - php

The Zend Form is proving to be a bit tricky for me, even as much as I am working with it lately...
I have this form and I am attempting to dynamically create the several checkboxes for it. It is working out alright, except I cannot seem to get the 'value' attribute to change.
In my Zend form class I have this snippet...
// psychotic symptoms
$this->addElement('checkbox', 'psychoticsymptom', array(
'label' => 'psychoticsymptom',
'name' => 'psychoticsymptom',
));
In my view (phtml) I am calling it like this...
<div class="element">
<?php // Psychotic Symptoms
$Criteria = new Criteria();
$Criteria->add( DictionaryPeer::CATEGORY, 'MAR: Psychotic Symptoms' );
$Criteria->addAscendingOrderByColumn( 'Ordinal' );
$this->PsychoticSymptomsList = DictionaryPeer::doSelect( $Criteria );
foreach( $this->PsychoticSymptomsList as $Symptom ) {
$form->psychoticsymptom->setValue($Symptom->getDictionaryId());
$form->psychoticsymptom->setAttrib('name', $Symptom->getWord());
echo $Symptom->getDictionaryId(); // prove my id is coming through... (it is)
$form->psychoticsymptom->getDecorator('label')->setTag(null);
echo $form->psychoticsymptom->renderViewHelper();
$form->psychoticsymptom->setLabel($Symptom->getWord());
echo $form->psychoticsymptom->renderLabel();
echo '<br />';
}
?>
</div>
Everything seems to be working fine, except the value attribute on each checkbox is rendering a value of '1'. I have tried moving the 'setValue' line to several different positions, as to set the value before the form element renders but I am having no luck getting this to work. It's worth any effort to me because I need to do the same type of operation in many areas of my application. I would have done this a bit different too, but I am re-factoring another application and am trying to keep some things unchanged (like the database for instance).
Any help is much appriciated
Thanks

you can try to overwrite the "checkedValue" and "uncheckedValue". check this reference
$this->addElement('checkbox', 'psychoticsymptom', array(
'label' => 'psychoticsymptom',
'name' => 'psychoticsymptom',
'checkedValue' => 'checked Value',
'uncheckedValue' => 'unchecked Value'
));

You seem to only have one psychoticsymptom element "checkbox" which your adding (changing) the value too for each $this->PsychoticSymptomsList.
Maybe you would be better off using a multicheckbox element instead.

Related

Yii active dropdownlist with optgroup

I try to create dropdown-list with Yii, using listData and activeDropDownList.
I use the examples found on the web, but it refuses to create the optgroups for me.
$data = CHtml::listData(MyModel::model()->getEntries(0), 'id', 'text', 'group');
Generates an array as expected:
Array([group1] => Array([10]=>FirstEntry, [20]=>SecondEntry),
[group2]=>Array([30]=>firstEntryGroup2, [40]=>firstEntryGroup2))
And so on. So it's an associative array filled with sub-arrays...
But when I use
echo CHtml::activeDropDownList($model, 'dropdownName', $data);
All I get is a flat dropdown without the optgroups. Just the entries from the sub-arrays...
Yii 1.1.6 (I read something about safe-attributes and tried to implement it, but with no success...
The old answer below is incorrect. Sorry. You create optgroups using a 'group' attribute in your drop down data array.
array(
array('id'=>256,'text'=>'TV','group'=>'Electrical'),
array('id'=>257,'text'=>'Radio','group'=>'Electrical'),
);
http://www.yiiframework.com/forum/index.php/topic/6903-how-can-i-generate-a-select-list-with-optgroup/
Old answer:
There is a great gist here that shows how do create what you're after: https://gist.github.com/StandardNerd/2909111
<?php echo CHtml::dropDownList('Cars', 'car_id', array(
'Mazda'=>array(
'mazda-rx7'=>'RX7',
'mazda-rx5'=>'RX5',
),
'Volvo'=>array(
'volvo-b9tl'=>'B9TL',
'volvo-l90e-radlader'=>'L90E Radlader',
),
)); ?>
You're currently using an activeDropDownList which should only be different because you add your $model variable instead of 'Cars' and tweak the function
One of solutions is anonymous function.
$data = CHtml::listData(
MyModel::model()->getEntries(0),
'id',
'text',
function(MyModel $aMyModelInstance){
return $aMyModelInstance->getLocalizedGroupNameForThisInstance();
});

Yii CArrayDataProvider Keyfield As Button Id In CGridView

My issue is two-fold. First, I'm unable to correctly set the keyField for CArrayDataProvider, all I'm getting back is a string instead of a value. Second, I'm trying to use the keyField inside of CArrayDataProvider to set an id on the button in each row inside of CGridView. The reason I want to do this is so that I can pass the id value onward to an ajax function (if there's a better way to do this in Yii, I'm all ears). Any help would be much appreciated, thanks in advance!
I also posted this question once on Yii's forums. I normally wouldn't repost, but I have had a hard time getting answers there, as opposed to stack overflow, you guys are the best! Here's the link to my original post if anyone is interested.
Here is how I'm building the array that I'm using as my RAW data:
foreach ($items as $item) {
$tableRow = array("id"=>$item["Id"], "Organization"=>$item["Organization"], "Roles"=>$item["Roles"]);
$return_items[] = $tableRow;
}
Here is the CArrayDataProvider setup I'm using. I noticed that 'keyField' is not being given the id value, just the string 'id':
$dataProvider=new CArrayDataProvider($return_items, array(
'keyField'=>'id',
'sort'=>array(
'attributes'=>array(
'Organization',
'Roles',
),
),
'pagination'=>array(
'pageSize'=>10,
),
));
Lastly, here is the CGridView I'm trying to setup in the view. All that appears on the button is the id tag, but no value:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$authItems,
'columns'=>array(
'Organization',
'Roles',
array('name'=>'',
'type'=>'raw',
'htmlOptions'=>array('id'=>'id'),
'value'=>'CHtml::button("Edit Roles", array("data-toggle"=>"modal", "data-target"=>"#roles-modal"))'),
),
));
Try passing it via CHtml::button which you have already applied. E.g.
'value'=>'CHtml::button("Edit Roles", array(
"id"=>$data["id"],
"data-toggle"=>"modal",
"data-target"=>"#roles-modal"
))'),

The request has been black-holed - CakePHP

I'm using CakePHP's SecurityComponent. And it's very essential as it saves forms from CSRF attacks. My project has total 10-12 forms and this is my first CakePHP project. After enabling SecurityComponent I was in a bit trouble but could get rid off after some careful minutes. This is the last form of my project and seems everything is correct to me but still the form is being black holed :(. Can anybody please tell me the problem? I don't want to disable CSRF checking or SecurityComponent. Here is my view code:
<?php
echo $this->Form->create('Record');
?>
<script type="text/javascript"> var me = new MetroExam(); </script>
<div class="exam_paper">
<div class="question_box" id="q_b">
<div class="q_n_a_header">
<div class="instructions">
<b>Instructions:</b><br>
<?=$inst['value_text']; ?>
</div>
<div id="timer">Please wait</div>
</div>
<div id="q_paper">
<img id="q" style="display: none;" src="/oes/<?=$exam['path'].'?ts='.time(); ?>">
<img id="loading_img" src="/oes/img/loading.gif">
</div>
</div>
<div class="ans_box" id="a_b">
<!-- information about answer paper. !important -->
<?php
$i = 0;
//these fields are essential for evaluating ans paper
echo $this->Form->hidden('submit', array('value' => 'true'));
echo $this->Form->hidden('start_time', array('value' => ''));
echo $this->Form->hidden('end_time', array('value' => ''));
echo $this->Form->hidden('duration', array('value' => ''));
echo $this->Form->hidden('valid', array('value' => ''));
echo $this->Form->hidden('passed', array('value' => ''));
//options for all radio
$options = array(
'1' => 'A',
'2' => 'B',
'3' => 'C',
'4' => 'D'
);
if($exam['choices'] == 5){
$options['5'] = 'None';
}
$questions = (int)$exam['questions']; // 40 <= $exam['questions'] <= 100
$i = 1;
while($questions--){
echo '<div class="'.(($i%2)==1?'each_answer_even':'each_answer_odd').'" id="ans-'.$i.'">';
echo '<div class="q_number">'.($i <= 9 ? '0'.$i : $i).'</div>';
$name = 'ans'.str_pad($i, 3, '0', STR_PAD_LEFT);
$attributes = array('empty' => false, 'legend' => false, 'onclick' => 'me.answer_click('.$i.')');
echo '<div class="mcq">'.$this->Form->radio($name, $options, $attributes).'</div>';
echo '</div>';
$i++;
}
echo $this->Form->end('Submit');
?>
</div>
</div>
This is basically a MCQ exam form. Where each group has 4 or 5 radio buttons and total 40 to 100 groups in a form. I'm using CakePHP 2.4. Thanks in advance.
As per the comments, the problem appears because you are changing the hidden values of the form. The way SecurityComponent works, is that it "locks" the name of the fields, so an evildoer can't add new fields or change the values once the form is sent. But it is even more strict with the hidden values, because it locks the field name and value. So by changing it with jQuery you're blackhole-ing your own form.
There's a nice little post where I learned this, take a look at it. The author there also explains two ways of bypassing this problem. One is to disable the security for hidden fields, so the hash calculated for the token doesn't include those values... which isn't really secure...
And another solution is to modify the FormHelper, and tell it to "lock" the hidden fields names but not the values. I don't remember what version of Cake the author uses for the example, but the code given there should be practicaly the same. So with that solution, you can tell the form to not be so strict with you with an option array.
Oh, and the other option given there (this is what I normally use) (I just read it now there... I thought I figure that on my own... oh well), is to just use normal input text fields for the ones you want hidden, and add a css style like display:none.
It's up to you what you think is best. I like the css option because is simpler, and really, if someone is going to mess with my css evily (with firebug or something like that), they might just as well do it with the values of hidden fields, it doesn't require any more effort. You should take all the extra steps and verifications when handling that form submission anyway. But like I said, up to you which do you think is best for your situation.
In addition to what was already posted, here's something else what might be causing the problem: in my case, a hidden input had it's name overwritten.
$this->Form->create('ExampleModel'):
$this->Form->input('foo_bar', array(
'type' => 'hidden',
'name' => 'foo_bar',
));
As a result, the final $this->request->data had the corresponding key $this->request->data['foo_bar']. It was not within the $this->request->data['ExampleModel'] array, and that's what the problem was.
To fix the issue, I had to remove the name key from the template, making the input belong to the model's data, and then just change the controller to accept that value.
Hope this helps someone else.
Update: this would also work on a form not attached to any model, e.g.:
$this->Form->create(false, array(
'url' => '/example',
)):

CodeIgniter: Validate form with multidimensional POST data

So the framework is CodeIgniter 2.0.2. I have a form that has groups of fields that correspond to rows in a database. The names of the fields are in the format:
opt[0][foo]
opt[0][bar]
opt[1][foo]
opt[1][bar]
etc...
The index (1,2,etc...) does not correspond to row IDs in the database, it is simply a way to split up the groups of fields. There may be gaps in the index as users are able to add and remove an arbitrary number of the field groups. All groups are identical, that is, they contain exactly the same set of fields with the same second level names.
I want to be able to use CodeIgniter's validation library to validate the form and (p)re-populate as necessary. I've found plenty of posts (in addition to the excellent CI user guide) on the pre-populating and I know how to get the working with the re-populating in general. However, this is the first time I've had to try it with the indexed field names as above. I've tried the below and it doesn't work:
array(
'field' => 'opt[][foo]',
'label' => 'Foo',
'rules' => 'required'
)
I'm guessing I was just hoping for too much and CodeIgniter doesn't support what I need it to do. Extending the existing form validation library is an option so if anyone has been in the same situation and can provide some tips that would be very welcome.
UPDATE:
Just a little extra info, I've also tried validating a specifically indexed field (see below) and that also didn't work... As I understand it multidimensional validation should work in the specific case:
array(
'field' => 'opt[0][foo]',
'label' => 'Foo',
'rules' => 'required'
)
The following controller code works for me on CI 2.0.2
public function test() {
$this->load->library('form_validation');
$this->load->helper('form');
$this->form_validation->set_rules('test[test1][test2]', 'Test', 'required|valid_email');
$this->form_validation->run();
echo validation_errors();
echo form_open($this->uri->uri_string());
echo form_input('test[test1][test2]', set_value('test[test1][test2]'));
echo form_submit();
echo form_close();
}
You can use this to loop through the opt variable and set validation rules for each input.
if(!empty($opt))
{
foreach($opt as $id => $value)
{
$this->form_validation->set_rules('opt[' . $id . '][foo]', 'Foo', 'required');
$this->form_validation->set_rules('opt[' . $id . '][bar]', 'Bar', 'required');
}
}
You should take a look at the callback functions for the validating class - this should help you accomplish what you need for validation.

How to Zend_Dojo_Form_Element_FilteringSelect onchange submit

Well the title pretty much says it all. I had:
$strata = new Zend_Form_Element_Select('strata');
$strata->setLabel('Select a strata: ')->setMultiOptions($this->stratalist)->setAttrib('onChange', 'this.form.submit()');
Then I need to use some fancy dojo form elements in other forms. So I decided to make them all look the same and did this:
$strata = new Zend_Dojo_Form_Element_FilteringSelect('strata');
$strata->setLabel('Select a strata: ')->setMultiOptions($this->stratalist)->setAttrib('onChange', 'this.form.submit()');
It shows up and looks fine, but the form is not submitted when I change the FilteringSelect. If I look at the HTML that is rendered, sure enough:
<select name="strata" id="strata" onChange="this.form.submit()">
I suspect that Dojo elements cannot or do not work like this. So how do I make this form submit when I change the FilteringSelect?
Here it is:
When defining the form, give it an id:
$this->setName('StrataSelect');
or
$this->setAttrib('id', 'StrataSelect');
Then the onChange event uses getElementById:
$strata = new Zend_Dojo_Form_Element_FilteringSelect('strata');
$strata->setLabel('Select a strata: ')->setMultiOptions($this->stratalist)->setAttrib('onChange', "document.dojo.byId('StrataSelect').submit();");
or
$strata->setLabel('Select a strata: ')->setMultiOptions($this->stratalist)->setAttrib('onChange', "document.getElementById('StrataSelect').submit();");
Why this now works and none of the "old school" submit() calls probably has something to do with dojo handling the onchange event. So submit or this.form are not objects, methods, etc etc etc.
I don't want to put any javascript this form depends on into the view. I want this form to be "portable". So therefore I don't want to use dojo.connect
There are probably better ways to do this. So I'll leave this unanswered for now.
Do you have parseOnLoad enabled? If you're building the form in php you can do this:
$form = new Zend_Form_Dojo();
$form->addElement(
'FilteringSelect',
'myId',
array(
'label' => 'Prerequisite:',
'autocomplete' => true,
'jsId' => 'myJsId',
),
array(), //attributes
array( //your select values
'id1' => 'name1',
'id2' => 'name2',
'id3' => 'name3',
)
);
you might need to set a few attributes on your $form.
try this:
$form->setAttribs( array('jsId'=>'MyFormName') );
Then in your onClick:
MyFormName.submit()
If your form passes validation (presuming you have some), it should submit.

Categories