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');
}
Related
I am new to phalcon and trying to learn this framework. I have created a simple form. Now, When I fill up the form, I am able to store the data in database. After submitting the form I want to be on the same page. Now the issue is, form is still have the filled data it is not clearing up. I have googled and found the clear() method to clear the form data but it seems that its not working. What to do?
Here is my code
//Controller
use Phalcon\Mvc\Controller;
class ProfileController extends Controller
{
public function indexAction()
{
// Add some local CSS resources
$this->assets->addCss("css/styles.css");
$this->assets->addCss("css/bootstrap.min.css");
// And some local JavaScript resources
$this->assets->addJs("js/jquery.js");
$this->assets->addJs("js/bootstrap.min.js");
}
public function createAction(){
//create object of model class
$profile = new Tbl_profile();
$profile->fname= $this->request->getPost('firstname');
$profile->lname= $this->request->getPost('lastname');
$profile->email= $this->request->getPost('email');
$success=$profile->save();
if($success) {
$this->flash->success("Profile created!");
//redirect to same page.
$this->dispatcher->forward(['action' => 'index']);
}else {
}
}
}
//views
<html>
<head>
<title>Title</title>
<?php $this->assets->outputCss(); ?>
</head>
<body>
<h4 class="ml-5 mt-2"> Create Profile</h4>
<?php echo $this->getContent(); ?>
<?php echo $this->tag->form("profile/create") ?>
<table class="table">
<tbody>
<tr scope="row">
<td>First Name</td>
<td><?php echo $this->tag->textField("firstname"); ?></td>
</tr>
<tr scope="row">
<td>Last Name</td>
<td><?php echo $this->tag->textField("lastname"); ?></td>
</tr>
<tr scope="row">
<td>Email</td>
<td><?php echo $this->tag->textField("email"); ?></td>
</tr>
<tr scope="row">
<td></td>
<td><?php echo $this->tag->submitButton("Create");?></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
Once you save the data to database, redirect to the controller instead of forwarding the request because forwarding the request won't reload the page.
$this->request->redirect('profile/index');
Read this what's the difference between redirect and dispatch in phalcon? for more information
You must create form class to have ability using $form->clear() method.
See the doc https://docs.phalconphp.com/cs/3.4/forms
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']);
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>
Currently I'm stuck writing a edit function for an order page using zend framework
Here is the situation:
One order consist of multiple items
Eg Order Number 1
Consists of Items
OrderListId OrderId title Sent dateSent trackingNumber
1 1 Book A 0 12/12/12 44444
2 1 Book B 1 10/01/12 51223
3 1 Book C 0 01/02/12 33353
and so on...
Please notes: the table are stored in a database
I need to have a page where the user can edit title, Sent, dateSent and trackingNumber fields.
How can I use zend form to populate these fields for edit. Since I want to have one page they can edit all these orderlist items. Rather then the user have to click back and forward to edit each order list item individually.
What's the best approach to this situation?
Thanks so much in advance!
I suggest using ZF Data Grid.
I had a problem similar to this awhile back and I came up with a solution where I just appended an update link to the end of the table row and populated a form for update while still displaying current information.
The following code samples were built before I knew what I was doing with ZF so they may be a little messy. I ended up with what amounts to single view that handles all of my CRUD operations.
**All css selectors removed for clarity
The display view:
<?php if (isset($this->leadtracks)): ?>
<form method="post" action="/admin/track/deletetrack">
<table>
<tr>
<th colspan="5"><?php $this->tableHeader() ?></th>
</tr>
<tr>
<th>Select</th>
<th>Shift</th>
<th>Days Off</th>
<th>Slots</th>
<th> </th>
</tr>
<tr>
<?php
//begin foreach loop using alternate syntax
foreach ($this->leadtracks as $lt):
?>
<td><input type="checkbox" name="trackid[]"
value="<?php
//trackid as value for checkbox
echo $lt->trackid
?>" style="width: 2px" /></td>
<td><?php
//find and display shift name
$lt->getShift();
?></td>
<td><?php $lt->getDays(); ?></td>
<td><?php echo $this->escape($lt['qty'])?></td>
<td><a href="<?php
//link to update action passing trackid and bidlocationid values
echo $this->url(array('module' => 'admin',
'controller' => 'track',
'action' => 'updatetrack',
'trackid' => $lt['trackid'],
'bidlocationid' => $lt['bidlocationid']))
?>">Update</a></td>
</tr>
<?php endforeach ?>
<tr>
<th colspan="5">
<input type="submit" name="submit" value="Delete Selected" />
</th>
</tr>
</table>
<?php endif; ?>
<!-- further code removed for brevity -->
</form>
The updateAction(), only one action for demonstration:
public function updatetrackAction() {
//get form set new label and assign to view
$form = new Admin_Form_Track();
$form->submit->setLabel('Update Track');
$form->addTrack->setLegend('Update A Track');
$this->view->form = $form;
try {
//check is post and is valid and get values from form
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
$data = $form->getValues();
$trackId = $data['trackid'];
//save update data to database
$update = new Model();
$update->update($trackId, $data);
//generate meesage
$this->_helper->flashMessenger->addMessage(Zend_Registry::get('config')
->messages->trackupdate->successful);
$this->getHelper('Redirector')->gotoSimple('addtrack');
} else {
//if form is not vaild populate form for resubmission
$form->populate($this->getRequest()->getPost());
}
} else {
//if form is not posted populate form with data from database
$trackId = $this->_getParam('trackid', 0);
if ($trackId > 0) {
$z = new Model();
$y = $z->getTrack($trackId)->toArray();
$form->populate($y);
}
}
} catch (Zend_Exception $e) {
$this->_helper->flashMessenger->addMessage($e->getMessage()->getTrace());
$this->_redirect($this->getRequest()->getRequestUri());
}
}
The addAction() and the deleteAction() are very similar and use the same view script called through the action() helper. The result is a page in which add, update and delete actions are performed from what the user perceives as one page(check box for multiple deletes and a link for update, every refresh displays current data). Although I do move the form from side to side as a sort of visual clue, though it really doesn't matter as all actions are available on each page.
the update view:
<div>
<h3><?php echo ucwords($this->escape(strtoupper($this->station) . ' - ' . $this->bidloc)); //page header ?></h3>
<?php echo $this->form //edit/add form ?>
</div>
<div>
<?php echo $this->action('displaytrack', 'track', 'admin') //display view ?>
</div>
I'm sure this can be done with the partial() view helper, without using the action() helper and I'm sure it can be done inline, I just haven't taken the time to figure out how to do it.
good Luck.
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']