Zend_Form : data table with checkboxes - zend-framework

I'd like to have a table of data coming from the DB in my form element, looking like the following :
+-----+-------------------------+-----------------------+
| | Number | Name |
+-----+-------------------------+-----------------------+
| [ ] | 123 | ABC |
+-----+-------------------------+-----------------------+
| [x] | 456 | DEF |
+-----+-------------------------+-----------------------+
| [x] | 789 | HIJ |
+-----+-------------------------+-----------------------+
It would allow to select several rows, like the MultiCheckBox element.
Here is the kind of markup I would like to have:
<table>
<thead>
<tr>
<th>Select</th>
<th>Number</th>
<th>Name</th>
</tr>
</thead>
<tr>
<td><input type="checkbox" name="subscribers[]" value="1234"></td>
<td>1234</td>
<td>ABC</td>
</tr>
<tr>
<td><input type="checkbox" name="subscribers[]" value="375950"></td>
<td>375950</td>
<td>DEF</td>
</tr>
<!-- and so on... -->
I can do it by hand but using Zend_Form would allow me to populate the form, retrieve the values easily and to have validation. I have other normal elements in my form.
Any idea on how to achieve this with Zend_Form ? Maybe a custom element and decorator ?
Thanks. Ask for more info if needed.
This question seems to be related: Zend_Form: Database records in HTML table with checkboxes
Marc

ok, so this is going to be a longer sort of answer
the Form
<?php
class Form_MyTest extends Zend_Form
{
public function init()
{
$element = $this->createElement('multiCheckbox', 'subscribers');
$element->setOptions(array('value1' => 'label1', 'value2' => 'label2'));
$this->addElement($element);
// ... other elements
}
}
Controller
<?php
class MyController extends Zend_Controller_Action
{
public function myTestAction()
{
$form = new Form_MyTest();
// ... processing logics
$this->view->assign('form', $form);
}
}
View
<form action="<?php echo $this->form->getAction(); ?>" method="<?php echo $this->form->getMethod(); ?>">
<table>
<thead>
<tr>
<th>Select</th>
<th>Number</th>
<th>Name</th>
</tr>
</thead>
<?php $values = $this->form->getElement('subscribers')->getValue(); ?>
<?php foreach($this->form->getElement('subscribers')->getMultiOptions() as $key => $value) : ?>
<tr>
<td><input type="checkbox" name="subscribers[]" id="subscribers-<?php echo $key; ?>" value="<?php echo $key; ?>" <?php echo in_array($key, $values) ? 'checked="checked"':''; ?>/></td>
<td><label for="subscribers-<?php echo $key; ?>"><?php echo $key; ?></label></td>
<td><label for="subscribers-<?php echo $key; ?>"><?php echo $value; ?></label></td>
</tr>
<?php endforeach; ?>
</table>
<!-- rest of form -->
</form>
A couple things are happening here.
I get the prepopulated values out of the form object:
<?php $values = $this->form->getElement('subscribers')->getValue(); ?>
I mark each checkbox as checked or not based on the array above
<?php echo in_array($key, $values) ? 'checked="checked"':''; ?>
EDIT IN RESPONSE TO COMMENT B/C COMMENTS DON'T SUPPORT PRE BLOCKS
the
$element->setOptions(
or
$element->setMultiOptions(
only accepts key => value pairs, so anything you want to do outside of key value pairs is going to be a little wierd. If your program allows you could pass another variable to the view, an array that uses the same keys as the multiCheckbox so
$this->view->assign('more_datums', array('value1' => array('col_1' => 'col_1_val'[, ...])));
and then in the foreach in the view use
$this->more_datums[$key]['col_1']

Related

$this->input->post() and $_POST is NULL in codeigniter

I am getting a problem in codeigniter where i have a view file called view.php.
<?php echo form_open('');?>
<table class="table">
<thead>
<tr>
<th>Full Name</th>
<th>Username</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo form_input('fullname1',$row_data['fullname']);?> </td>
<td><?php echo form_input('username1',$row_data['username']);?></td>
<td><?php echo anchor("welcome/save/".$row_data['rid'],form_button('button',"Save"));?></td>
</tr>
</tbody
</table>
<?php echo form_close();?>
and here is my save method
public function save($rid){
$arr=array('fullname'=>$this->input->post('fullname1'),
'username'=>$this->input->post('username1')
);
var_dump($_POST);
var_dump($arr);
}
both array varable giving me NULL values while the textboxes have the values Please Help.... Thanks
you need to add the url to your form_open method. Try
echo form_open("your_url");
give the path of your save method instead of your_url.
Also check documentation here
The form_open method demands a target url.
In View
# Syntax <?php echo form_open('controllerName/MethodName');?>
<?php echo form_open('welcome/save');?>
// remove this
<td><?php echo anchor("welcome/save/".$row_data['rid'],form_button('button',"Save"));?></td>
// Add this
echo form_submit('mysubmit', 'Submit Post!');
In Controller
public function save(){
$fullname= $this->input->post('fullname1');
$username = $this->input->post('username1');
echo "MY name is ".$fullname." UserName Is : "$username;
}
Read Form Helper Codeigniter and form-validation-using-codeigniter example

Disable or change validation for embedded form fields in Symfony1 form

I am trying to cancel validation in embedded forms based on a value from main form.
By default, embedded forms fields have validator option set to 'required'=>true. So it gets validated like that. If user leave any field blank, the form does not pass validation and blank fields get marked in template (different style).
What I am trying to do is to change option:"required" to false for all fields in embedded form.
I tried to do that in post validator callback method, but it seems that it is not possible that way.
The main form code:
class TestForma extends sfForm
{
public function configure()
{
$this->setWidgets(array(
'validate_items' => new sfWidgetFormChoice(array(
'choices' => array('no' => 'No', 'yes' => 'Yes'),
'multiple' => false,'expanded'=>true,'default' => 'no')),
));
$this->setValidators(array('validate_items' => new sfValidatorPass()));
$this->widgetSchema->setNameFormat('testforma[%s]');
$subForm = new sfForm();
for ($i = 0; $i < 2; $i++)
{
$form = new ItemForma();
$subForm->embedForm($i, $form);
}
$this->embedForm('items', $subForm);
$this->validatorSchema->setPostValidator(
new sfValidatorCallback(array('callback' => array($this, 'postValidate')))
);
}
Post-validator code:
public function postValidate($validator,$values)
{
$validatorSchema = $this->getValidatorSchema();
if($values['validate_items']=='no')
{
$itemsValidatorSchema = $validatorSchema['items'];
$itemsFieldsValidatorSchemes = $itemsValidatorSchema->getFields();
foreach($itemsFieldsValidatorSchemes as $itemValidatorScheme)
{
$itemValidatorScheme['color']->setOption('required',false);
$itemValidatorScheme['shape']->setOption('required',false);
}
}
return $values;
}
Embedded form class:
class ItemForma extends sfForm
{
public function configure()
{
$this->setWidgets(array(
'color' => new sfWidgetFormInputText(),
'shape' => new sfWidgetFormInput(),
));
$this->setValidators(array(
'color' => new sfValidatorString(array('required'=>true)),
'shape' => new sfValidatorEmail(array('required'=>true)),
));
$this->widgetSchema->setNameFormat('items[%s]');
}
}
Template code:
<form action="<?php echo url_for('weather/formiranje')?>" method="post">
<?php
foreach($form->getErrorSchema()->getErrors() as $e)
{
echo $e->__toString();
}
?>
<table>
<tfoot>
<tr>
<td colspan="2">
<input type="submit" value="OK" />
</td>
</tr>
</tfoot>
<tbody>
<tr><th>Main form</th></tr>
<tr><td><?php echo $form['validate_items']->renderLabel() ?>
<span class="<?php echo $form['validate_items']->hasError() ? 'rowError' : ''?>">
<?php echo $form['validate_items'] ?></span>
</td></tr>
<tr><td> </td></tr>
<tr><th>Embedded forms</th></tr>
<?php
foreach($form['items'] as $item)
{
?>
<tr>
<td><span class="<?php echo $item['color']->hasError() ? 'rowError' : ''?>">
<?php echo $item['color']->renderLabel() ?>
<?php echo $item['color'] ?></span>
</td>
</tr>
<tr>
<td><span class="<?php echo $item['shape']->hasError() ? 'rowError' : ''?>">
<?php echo $item['shape']->renderLabel() ?>
<?php echo $item['shape'] ?></span>
</td></tr>
<?php
}
echo $form['_csrf_token'];
?>
</tbody>
</table>
</form>
The way you organised it won't work because the post validator is run after all the field validators, so they've already been checked and marked as failed. (because the fields were required).
You could try the same approach you have here but with setting a preValidator instead of a postValidator. I think it should work then.
If it still won't work as expected what I would do is to change the default settings on the embedded form's fields to 'required' = false and use the postValidator. In the validator you could check whether or not you need to validate the embedded fields. If you need to validate them you can check if their values are set and if not you can throw errors for those fields. (I hope this is explained clearly)
Another thing you could try is to re-run the validation for the chosen fields. So something like that in your postValidator:
$itemValidatorScheme['color']->setOption('required',false);
$itemValidatorScheme['color']->clean($values['name_of_the_field']);

Access an id of a user in a table from a controller

PHP, Zend Framework, Apache, MySql.
I want to edit a user in a list by clicking its corresponding edit button.
when i click the edit button, the corresponding users id should be send to the controller from where it should be accessed.
But I cant seem to get the user id in the controller.
After getting the id , i want to populate the fields in edit.phtml with the data retrieved view model.
Since i cant access the id, i cant populate the fields.
The url is like /Sample/user/edit/2 where 2 is id of a user.
UserController.php
<?php
class UserController extends Zend_Controller_Action
{
protected $_user;
public function init()
{
/* Initialize action controller here */
$this->_user = new Application_Model_User();
}
public function indexAction()
{
// action body
}
public function listAllAction()
{
// action body
$this->view->users = $this->_user->listUsers();
}
public function registerAction()
{
// action body
if($this->getRequest()->isPost())
{
$data = array(
'user_uname' => $this->_request->getParam('uname'),
'user_pwd' => $this->_request->getParam('paswd'),
'user_address' => $this->_request->getParam('address')
);
$this->_user->insert($data);
}
}
public function editAction()
{
// action body
**$u_id = $this->_request->getParam('user_id');**
// print_R("Hi ".$u_id);
// exit;
if($this->_request->isPost())
{
$u_id = $this->_request->getPost('user_id');
//print_R("Hi ".$u_id);
//exit;
}
else
{
**$this->view->user = $this->_user->getUser($u_id);**
}
}
}
Model class
<?php
class Application_Model_User extends Zend_Db_Table_Abstract
{
protected $_name="tbl_user";
public function listUsers()
{
// action body
$sql = "select * from tbl_user";
$result = $this->_db->query($sql);
return $result->fetchAll();
}
public function getUser($id)
{
$query = "select * from tbl_user where user_id = ?";
return $this->_db->fetchRow($query,array($id));
}
}
ListUser.phtml
<html>
<head></head>
<body>
<b><center>List of Users</center></b>
<form name="list_users" method="post" action="">
<table>
<tr><th>ID</th>
<th>Name</th>
<th>Password</th>
<th>Address</th>
<th>Action</th>
</tr>
<?php foreach ($this->users as $usr): ?>
<tr>
<td><?php echo $usr['user_id'] ?></td>
<td><?php echo $usr['user_uname'] ?></td>
<td><?php echo $usr['user_pwd'] ?></td>
<td><?php echo $usr['user_address'] ?></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php endforeach; ?>
<tr>
<td colspan=2>Add More Users</td>
</tr>
</table>
</form>
</body>
</html>
edit.phtml
<html>
<head></head>
<body>
<form name="user_edit" method="post" action="<?php print $this->baseUrl(); ?>/user/edit">
<b><center>Edit Profile</center></b>
<table>
<tr>
<td>Username</td>
<td><input type="text" name="uname" id="uname1" value="<?php print $this->user['user_uname'] ?>"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="paswd" id="paswd1"/></td>
</tr>
<tr>
<td>Address</td>
<td><textarea type="text" name="address" id="address1"></textarea></td>
</tr>
<tr>
<td></td>
<td><input type='submit' name='edit_user' value='Update User'/></td>
</tr>
<tr>
<td colspan=2>See All Users</td>
</tr>
</table>
</body>
</html>
Thank you in advance..
I got the answer.
In usercontroller's editaction change the code $u_id = $this->_request->getParam('user_id'); to $u_id = $this->getRequest()->getParam('id');
Small change needed: change the following line:
<td>Edit</td>
to
<td>Edit</td>

Codeigniter - update table from form with checkbox

I'm trying to update a MySQL table with Codeigniter.
My model code is:
function update_customer_records($updatedrow)
{
$this->db->where('id',$this->input->post('id'));
$this->db->update('customers',$updatedrow);
}
My view is:
$attributes=array(
'name'=>'updatecustomer',
'id'=>'updatecustomer',
);
echo form_open('masterdata/manage_customers',$attributes);
?>
<table>
<tr>
<td> </td><td> </td><td>Customer Name</td><td>postalcode</td>
<tr>
<?php if(isset($records)) : foreach ($records as $row) : ?>
<tr>
<td>
<?php echo anchor('masterdata/customers_updated/'.$row->id, img(array('src'=>'images/delete_icon.png','border'=>'0','alt'=>'Delete'))); ?>
</td>
<td>
<input type=checkbox name="editcustomer[]" id="editcustomer[]" value="<?php echo $row->id ?>">
</td>
<td>
<input type="text" name="customername_<?php echo $row->id ?>" id="customername_<?php echo $row->id ?>" value="<?php echo $row->customer_name ; ?>" >
</td>
<td>
<input type="text" name="customername_<?php echo $row->id ?>" id="customername_<?php echo $row->id ?>" value="<?php echo $row->postalcode ; ?>" >
</td>
</tr>
<?php endforeach ; ?>
</table>
<input type="submit" value="Update Selected">
<?php else : ?>
<h2> No Records Found</h2>
<?php endif; ?>
<?php echo form_close(); ?>
My controller is :
function manage_customers()
{
$data['title']="Manage Customers";
//query model to get data results for form
$data=array();
if($query=$this->model_master_data->get_records()){
$data['records']=$query;
$this->load->view("master_data/view_master_data_header",$data);
$this->load->view("master_data/view_master_data_nav");
$this->load->view("master_data/view_content_master_data_manage_customers",$data);
$this->load->view("master_data/view_master_data_footer");
$editcustomer = $this->input->post('editcustomer');
if(isset($editcustomer)){
//begin outputting id of selected checkbox
foreach ($editcustomer as $row) :
echo $row;
$updatedrow=array(
'id'=>$row,
'postalcode'=>'44444'
);
$this->model_master_data->update_customer_records($updatedrow);
endforeach;
}
I have two issues :
How do I stop the foreach from running if a checkbox has not been checked.
How do I pass the array to the model correctly so that the update runs?
Thanks in advance as always.
First of all I found two fields in the form with the same name and id (given below) and in one field you are setting it's value customer_name and in another you are setting postalcode.
<td>
<input type="text" name="customername_<?php echo $row->id ?>" id="customername_<?php echo $row->id ?>" value="<?php echo $row->customer_name ; ?>" >
--^^--
</td>
<td>
<input type="text" name="customername_<?php echo $row->id ?>" id="customername_<?php echo $row->id ?>" value="<?php echo $row->postalcode ; ?>" >
--^^--
</td>
So I think (probably) the name and id of the second field should be postalcode according to it's value.
Also you don't need to worry about foreach loop because the code inside the loop ll run only if there are checked check boxes on the form because unchecked check boxes won't be submitted but you can check and run the loop using following code
if( $this->input->post('editcustomer') != false )
{
foreach ($editcustomer as $row)
{
// code here
}
}
The if condition will return false if the editcustomer is not found or not submitted with the form. Also there is no id field in your form and in this case you can't use $this->input->post('id'), so if you need to check the check box id in the where clause of your model then you can use
In The controller :
if( $this->input->post('editcustomer') != false )
{
$this->load->model('model_master_data');
foreach ($editcustomer as $row_id)
{
$data = array( 'postalcode' => '44444' );
$this->model_master_data->update_customer_records( $row_id, $data );
}
}
I don't think you need to pass 'id'=>$row, because you probably don't wan't to update this field. Also you should use form validation to check the form input before updating the record (you may set the postcode field required to bound the user to enter a postcode).
In The Model :
function update_customer_records( $id, $data )
{
$this->db->where( 'id', $id );
$this->db->update( 'customers', $data );
}
So it'll do something like this (pseudo code)
update the customers table set `postalcode` = '44444' where `id` = $id
Update :
I think you can also use the update_batch.
In The controller :
if( $this->input->post('editcustomer') != false )
{
$data = array();
foreach ($editcustomer as $row_id)
{
$data[] = array( 'id' => $row_id, 'postalcode' => '44444';
}
$this->load->model('model_master_data');
$this->model_master_data->update_customer_records( $data );
}
In The Model :
function update_customer_records( $data )
{
$this->db->update_batch('customers', $data, 'id');
}
Duplicate topic with "Codeigniter update mysql table from form with CI" ?
how do I stop the foreach from running if a checkbox has not been checked.
You don't have to stop the foreach from running if a checkbox has not been checked.
Because $editcustomer variable only contain checkbox checked.
How do I pass the array to the model correctly so that the update runs?
Your model is wrong. It should be:
public function update_customer_records($updatedrow)
{
$this->db->update('customers', $updatedrow);
}
You don't need to write $this->db->where('id',$this->input->post('id')); (and it's wrong, because you can't use $this->input->post() in your model) because you already pass id in $updaterow.
Edit : I'm sorry, I read your code too quickly!
function update_customer_records($updatedrow)
{
$this->db->where('id',$this->input->post('id'));
$this->db->update('customers',$updatedrow);
}
...is correct. Alternatively, you can write it in a shorter way:
function update_customer_records($updatedrow)
{
$this->db->update('customers', $updatedrow, array('id' => $this->input->post('id')));
}

Symfony forms post

I read about Symfony forms and i have simple question :
i Make 2 templates "test" and test1 . I want to post forms values of
test to test1 and after to show them with echo.
In test i put:
form action="<?php echo url_for('maraton/test') ?>" method="POST" />
<table>
<tr>
<?php echo $form?>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="submit" />
</td>
</tr>
</table>
</form>
my action is :
public function executeTest(sfWebRequest $request)
{
$this->form = new AthletesForm();
}
public function executeTest1(sfWebRequest $request)
{
$this->form = new AthletesForm();
if ($request->isMethod('post'))
{
$values = $this->form->getValues();
}
When creating a form you create it using an action :
public function executeContact($request)
{
$this->form = new sfForm();
}
Then to display that form you use a template
<?php echo $form->renderFormTag('foo/contact') ?> // this route "foo/contact" points to the action that will process the submit
<table>
<?php echo $form ?>
<tr>
<td colspan="2">
<input type="submit" />
</td>
</tr>
</table>
</form>
Then to process the form submit you use either the same action as above or a seperate action :
if ($request->isMethod('post'))
// this if statement would be added if you used the same action to
// create / process the submit of the form
{
$this->form = new sfForm(); // create an empty form object
$this->form->bind($request->getParameter('contact'));
// merges (binds) the post data with the form
if ($this->form->isValid()) // if the data is valid
{
// Handle the form submission
$contact = $this->form->getValues();
$name = $contact['name'];
// Or to get a specific value
$name = $this->form->getValue('name');
// Do stuff
// persist to database / save to file etc
$this->redirect('foo/bar');
}