Overwriting zend form checkbox - php

I have a problem with the zend form checkbox.
$this->addElement('checkbox', 'languages', array(
'label' => 'Languages',
'class' => 'check_1',
'name' => 'checkset',
'checkedValue' => '1',
'uncheckedValue'=> '0'
));
I made this checkbox and overwritten the checkedValue and uncheckedValue but when I debug it, it has totally different values:
$values = $form_duplicate->getValues();
var_dump($values);
This is the result:
["languages"]=> string(1) "0"
I can't understand where is the problem. I looked up on the zend documentation page and this is how it must be.

I'm not sure I understand your problem, but you can use the setCheckedValue and setUncheckedValue methods to change defaults values like this:
$langages = new Zend_Form_Element_Checkbox('languages', array(
'label' => 'Languages',
'class' => 'check_1',
'name' => 'checkset'
));
$langages->setCheckedValue('value_check');
$langages->setUncheckedValue('value_uncheck');
$this->addElement($langages);
And to recover your values:
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
// isValid($formData) filled the form with the datas returned
if ($form_duplicate->isValid($formData)) {
// treatment
}
$values = $form_duplicate->getValues();
var_dump($values);
}

Related

How can I edit a field of a form in my controller?

I'm having trouble formulating a solution for 'editing' a field of my form in my controller.
Here's what I have:
I have a symfony2 form registered as a service that I call in a function in my controller. I am removing a bunch of fields that aren't necessary for this other form I am directing my users to and then adding a few others.
(I realize I could create another form and create another service and such but for my purpose this would be a bit overkill. I'm doing it this way because the form functions the same, however some fields are not needed and a few new specific ones are.)
I would now like to essentially 'edit' one field in this form... The 'occupation' field. This field is a choice field acting as radio buttons populated by an array of choices. It's required and has no empty_value requirement in its original state.
I would like to edit it in my controller function to have the same exact values however with a required value of false and an empty_value of null.
With the commented out code below the result is a dissapearance of the occupation field in my 'new' form and it is replaced by an empty drop down. I realize it's because I'm overriding the whole field below, but I cannot figure out how to simply edit it.
Code:
/**
* Explanation of addAndRemoveFieldsInRegisterForm function:
* The function gets the 'registration' form and removes any
* fields not needed for the 'in_registration' form
* and then adds the necessary fields to the form.
*/
private function addAndRemoveFieldsInRegisterForm($user)
{
$form = $this->createForm('user_registration', $user);
// http://stackoverflow.com/questions/10920006/pass-custom-options-to-a-symfony2-form ---
// --- use that to help. Look at changing the value of array.
$form->remove('title');
$form->remove('company');
$form->remove('username');
$form->remove('city');
$form->remove('state');
$form->remove('country');
$form->remove('gender');
$form->remove('age');
$form->remove('roles');
// $form->remove('occupation');
// $pr = $form->get('occupation');
// $pr->set('required' => false);
// $form->get('occupation')->add('required'=>false, 'empty_value'=>null);
// $form->add('occupation','choice', array(
// 'required' => false,
// 'empty_value' => null,
// ));
// echo "<pre>";
// var_dump(get_class_methods($form));die;
$form->add('occupation','choice', array(
'required' => false,
'empty_value' => null,
));
$form->add('canEmail', 'checkbox', array(
'label' => 'Can Email?',
'required' => false,
));
$form->add('sendEmail', 'choice', array(
'label' => 'Send Welcome Email? ',
'required' => true,
'mapped' => false,
'expanded' => true,
'choices' => array(
"yes" => "Yes",
"no" => "No"
),
));
return $form;
}
Original Form (the one that's used as a service)
private $requireOccupation;
$this->requireOccupation = true;
->add('occupation','choice', $options['occupation'])
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$occupation = array(
"label" => "Which of these currently describes you best? (Occupation):",
"expanded" => true,
'required'=> $this->requireOccupation,
"choices" => array(
"X" => "X",
"B" => "B",
"C" => "C",
"J" => "J",
),
'constraints' => array(
new NotBlank()
));
$resolver->setDefaults(array(
'occupation' => $occupation,
));
}
I think it is better to create another form. It can herit from your already defined form to change only the field you want
class SomeFormType extends OriginalFormType {
public function buildForm(FormBuilderInterface $builder, array $options) {
parent::buildForm($builder, $options);
$builder
->remove('someField')
->add('someField', 'choice', [
"expanded" => true,
"choices" => $yourArray
]);
}
It has the advantage to be mapped on different object
Firstly, I realize the way I wanted to solve this issue is odd when considering I could have created another form with either the fields I wanted to use or just the one field that needed to change and register the form as a service to use it elsewhere, but I was tasked to complete it this way.
Second, my solution is quite simple. I pass values into my form with a default value set in the form.
In the form:
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$requireOccupation = true;
$emptyValue = null;
//whatever other values you want to set here
$resolver->setDefaults(array(
'requireOccupation' => $requireOccupation,
'emptyValue' => $emptyValue,
));
}
and then on the field's properties:
$builder->add('occupation', 'choice', array(
"label" => "Some sort of label",
"required" => $options['requireOccupation'],
"empty_value" => $options['emptyValue'],
...
));
Now in the controller:
$form = $this->createForm('registration', $user, array(
'requireOccupation' => false, 'emptyValue' => null
));
call that where you want to generate your form while passing in the values you want to use for that form.
I am by no means an expert on Symfony and this solution would probably generate some issue with those who are. But it works for me.

Troubleshooting dynamic dropdowns in SugarCRM 6.5

I had asked a question here a while back about setting up database populated dropdowns for SugarCRM. I received a really good answer and, after more php studies and a dev instance running, I decided to give it a shot. The instructions I followed can be found here. After I run the repair and rebuild, I would expect to see the custom field in my Fields list under the module in studio, but have not been able to find it. The module is named Makers (a1_makers as a database table). For good orders sake, there were no errors when I repaired/rebuilt after saving the files. Per the instructions, I first created a php file with a custom function to query the database (custom/Extension/application/Ext/Utils/getMakers.php):
<?php
function getMakers() {
static $makers = null;
if (!$makers){
global $db;
$query = "SELECT id, name FROM a1_maker";
$result = $db->query($query, false);
$accounts = array();
$accounts[''] = '';
while (($row = $db->fetchByAssoc($result)) !=null) {
$accounts[$row['id']] = $row['name'];
}
}
return $makers;
}
?>
Then, I set 'function' field in Vardefs to point to the function (custom/Extension/modules/Maker/Ext/Vardefs/makers_template.php):
<?php
$dictionary['Maker']['fields']['list_of_makers'] = array (
'name' => 'list_of_makers',
'vname' => 'LBL_MKRLST'
'function' => 'getMakers',
'type' => 'enum',
'len' => '100',
'comment' => 'List of makers populated from the database',
);
?>
Unfortunately, there are no errors and the repair/rebuild runs fine. I am just unable to see the custom field when I go into studio. Can anyone please help point out what I may be doing wrong?
I would recommend checking existence of newly created field 'list_of_makers' in cache/modules/Maker/Makervardefs.php file. If new field definition exists in that file, try add 'studio' => 'visible' to custom/Extension/modules/Maker/Ext/Vardefs/makers_template.php to get something like this:
<?php
$dictionary['Maker']['fields']['list_of_makers'] = array (
'name' => 'list_of_makers',
'vname' => 'LBL_MKRLST'
'function' => 'getMakers',
'type' => 'enum',
'studio' => 'visible'
'len' => '100',
'comment' => 'List of makers populated from the database',
);
Try to edit your custom/modules/Maker/metadata/editviewdefs.php manually and insert field definition by hand in proper place if everything above won't work.
$dictionary['Maker']['fields']['list_of_makers'] = array (
'name' => 'list_of_makers',
'vname' => 'LBL_MKRLST'
'function' => 'getMakers',
'type' => 'enum',
'studio' => 'visible'
'len' => '100',
'comment' => 'List of makers populated from the database',
'studio' => array(
'listview' => true,
'detailview' => true,
'editview' => true
),
);

remove validation zend form element javascript/jquery

I want to disable the validation on one of the zend form element based on the input on another element on the same form. I need to achieve this using javascript/jquery. Something very common but very surprisingly couldn't find it over the internet.
e.g.
In the controller:
$oFormMassEdit = new Account_Form_Returns_Return();
$this->view->form = $oFormMassEdit;
In Account_Form_Returns_Return's constructor:
$oNoteElement = new Zend_Form_Element_Textarea('option', array(
'required' => true,
));
$this->addElemet($oNoteElement)
$oReasonElement = new Zend_Form_Element_Select('note', array(
'multiOptions' => array (
'return' => 'return',
'defect' => 'Kaput',
'other' => 'Anderer Grund'
),
'required' => true,
));
$this->addElement($oReasonElement);
$this->addDisplayGroup(array('note', 'option'), 'main', array('legend' => 'Retouren'));
$this->addElement('button','send', array(
'type' => 'submit',
'label' => 'Methode speichern',
));
and finally in the view,
<?= $this->form; ?>
Javascript can't (not in a sensible way) switch Zend_Form configuration. What you can do is changing the 'required' param for certain form fields on validation. For example; If you want to allow fieldTwo to be empty if fieldOne has 'desiredValue' as value you can achieve this using the following function in your form:
public function isValid($data) {
if('desiredValue' == $data['fieldOne'])) {
$this->getElement('fieldTwo')->setRequired(false);
}
return parent::isValid($data);
}

CakePHP: "GET" form does not auto-populate form fields after submission

I'm using Cake 2.3.0. If I submit my form using POST, the selected form fields carry over however if I submit my form using GET, all of the form fields return to their default values.
Is there a way to make the GET submission to work like that of the POST?
Here's my contorller:
class ListingsController extends AppController {
public function results() {
$conditions = array(
'Listing.Beds >=' => $this->request->query['beds'],
'Listing.ListingStatus >=' => $this->request->query['status'],
);
$this->paginate = array(
'conditions' => $conditions,
);
$this->set('listings', $this->paginate());
}
}
Here's what my view looks like.
echo $this->Form->create(null, array(
'controller' => 'listings',
'action' => 'results',
'type' => 'get'
));
echo $this->Form->input('name');
$beds = array('1' => '1+', '2' => '2+', '3' => '3+', '4' => '4+', '5' => '5+');
echo $this->Form->input('beds', array('options' => $beds));
$status = array('Active' => 'Active', 'Pending' => 'Pending', 'ActivePending' => 'Active and Pending');
echo $this->Form->input('status', array('options' => $status));
echo $this->Form->end('Update');
So basically if I change 'type' => 'get' to 'type' => 'post' it works just fine. But I need to be able to do this via GET.
Thanks
I agree that this is annoying (IMO CakePHP should be smart enough to automatically determin 'where' to get its data from, based on the 'type').
You'll have to copy the 'query' of the request to the 'data' of the request;
$this->request->data = $this->request->query;
Not behind my computer to test it (as usual, lol), but should probably work.
Try adding this to your controller:
$this->request->data = $this->params['url'];
My solution:
$this->params->data = array('Tablefilter' => $this->params->query);
where "Tablefilter" depends on form definition (usually the model name)
$this->Form->create('Tablefilter', array('type' => 'get'))
Use PRG. Checkout this plugin.
What I ended up doing was looping through the $this->request->query array and pass those values to the matching $this->request->data.
So I added this:
foreach($this->request->query as $k => $v){
$this->request->data['Listing'][$k] = $this->request->query[$k];
}
Which ultimately gave me this:
class ListingsController extends AppController {
public function results() {
foreach($this->request->query as $k => $v){
$this->request->data['Listing'][$k] = $this->request->query[$k];
}
$conditions = array(
'Listing.Beds >=' => $this->request->query['beds'],
'Listing.ListingStatus >=' => $this->request->query['status'],
);
$this->paginate = array(
'conditions' => $conditions,
);
$this->set('listings', $this->paginate());
}
}
I'm not going to accept this as the answer though as I don't know if this is the optimal or suggested way to do it. But it works for me for now.
This works for me :
$this->request->data['Cluster'] = $this->params->query ; //controller side
Form definition:
$this->Form->create('Cluster',array('type'=>'get'));

Cakephp $this->request->data returns id of select field instead of value which is needed and shown in the select field

I have a CakePHP controller like this:
$this->loadModel('Project');
$list2 = $this->Project->find( 'list', array(
'fields' => array('Project.project'),
'conditions' => array('Project.user_id' => $userId)
));
$this->set($list2, 'list2');
$this->loadModel('Distance');
if(!empty($this->request->data)){
$this->Distance->create();
if ($this->Distance->save($this->request->data)) {
$this->Session->setFlash('Saved.');
// $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('FAILED');
}
}else{
// $this->Session->setFlash('test');
}
and a view like this:
echo $this->Form->input('Distance.project', array('options' => $list2, 'label' => false, 'empty' => '(choose one)' ;
But I get inserted to the database the id of the project instead of the project name.
I never have such problems working with the fields - just with a list of data.
Any idea why it happens?
It's normal ... The $list2 it's and array ... and the values of the options are the indexes from that array.
If you want to insert only the project name you need to change $list2 with $list2['project_name']. You need to remove or replace the indexes of $list2.
LE: take iexiak example. He change also the code for you.
$list2 = $this->Project->find( 'list', array(
'fields' => array('Project.project'),
'conditions' => array('Project.user_id' => $userId)
)
);
This is because $list2 automatically creates a list of ID => project; and when you use that as input for your form it automatically creates the drop down to reflect this. This is generally the best practice, to link to ID's instead of to descriptions, as ID's do not change as often. The below should get you exactly what you want though:
$list2 = $this->Project->find( 'list', array(
'fields' => array('Project.project','Project.project'),
'conditions' => array('Project.user_id' => $userId)
)
);

Categories