I wrote a function that has two forms that are activate separately, persisting same Entity. First is activated for input field and second for random generated field.
But when I click submit it activates both forms one after other. If used conditions to prevent that but I seems that it doesn't work.
My code:
$id = $request->get('id');
$user = $this->container->get('account')->getUserRepository()->find($id);
$form1 = $this->createFormBuilder()
->add('password', PasswordType::class, array(
'label' => 'Enter New Password',
'attr' => ['class'=>'form-control']))
->add('save', SubmitType::class, array(
'label' => 'Send', 'attr' => ['class' => 'btn btn-primary action-save']
))
->getForm();
$form2 = $this->createFormBuilder()
->add('password', PasswordType::class, array(
'label' => 'Generate New Password',
'disabled'=> true,
'attr' => ['class'=>'form-control']))
->add('save', SubmitType::class, array(
'label' => 'Send',
'attr' => ['class' => 'btn btn-primary action-save']
))
->getForm();
$form1->handleRequest($request);
if($form1->isSubmitted() && $form1->isValid()) {
$this->addFlash(
'notice',
'You successfully changed the password!'
);
$data = $form1->getData();
$new_password = $data['password'];
$encoder = $this->container->get('security.encoder_factory')->getEncoder($user);
$new_pwd_encoded = $encoder->encodePassword($new_password);
$oneTimePsw = '';
$user->setPassword($new_pwd_encoded);
$manager = $this->getDoctrine()->getManager();
$manager->flush();
}
$form2->handleRequest($request);
if($form2->isSubmitted() && $form2->isValid()) {
$this->addFlash(
'notice',
'Password is successfully generated!'
);
$data = $form2->getData();
$new_password = $data['password'];);
$new = $this->get('member.account')->generateRandomPassword();
$oneTimePsw = '';
$user->setPassword($new);
$manager = $this->getDoctrine()->getManager();
$manager->flush();
}
return $this->render('#AdminTemplates/admin/reset_password.html.twig', array(
'form1' => $form1->createView(),
'form2' => $form2->createView()
));
My twig
<div id="setPassword" style="display:none;">
{{ form_start(form1) }}
{{ form_end(form1) }}
</div>
<div id="generatePassword" style="display:none;">
{{ form_start(form2) }}
{{ form_end(form2) }}
</div>
I think your problem is a simple if else anidation problem, when i had the same issue this is what i did:
$id = $request->get('id');
$user = $this->container->get('account')->getUserRepository()->find($id);
$form1 = $this->createFormBuilder()
->add('password', PasswordType::class, array(
'label' => 'Enter New Password',
'attr' => ['class'=>'form-control']))
->add('save', SubmitType::class, array(
'label' => 'Send', 'attr' => ['class' => 'btn btn-primary action-save']
))
->getForm();
$form2 = $this->createFormBuilder()
->add('password', PasswordType::class, array(
'label' => 'Generate New Password',
'disabled'=> true,
'attr' => ['class'=>'form-control']))
->add('save', SubmitType::class, array(
'label' => 'Send',
'attr' => ['class' => 'btn btn-primary action-save']
))
->getForm();
$form1->handleRequest($request);
$form2->handleRequest($request);
if($form1->isSubmitted() && $form1->isValid()) {
$this->addFlash(
'notice',
'You successfully changed the password!'
);
$data = $form1->getData();
$new_password = $data['password'];
$encoder = $this->container->get('security.encoder_factory')->getEncoder($user);
$new_pwd_encoded = $encoder->encodePassword($new_password);
$oneTimePsw = '';
$user->setPassword($new_pwd_encoded);
$manager = $this->getDoctrine()->getManager();
$manager->flush();
}else
if($form2->isSubmitted() && $form2->isValid()) {
$this->addFlash(
'notice',
'Password is successfully generated!'
);
$data = $form2->getData();
$new_password = $data['password'];);
$new = $this->get('member.account')->generateRandomPassword();
$oneTimePsw = '';
$user->setPassword($new);
$manager = $this->getDoctrine()->getManager();
$manager->flush();
}
return $this->render('#AdminTemplates/admin/reset_password.html.twig', array(
'form1' => $form1->createView(),
'form2' => $form2->createView()
));
This should work, because a user can't submit 2 forms at once. I also had a problem with the isValid() method so also try for testing taking it down.
Related
I'm following the official documentation example but I can't make it to work properly.
Summarizing, I have material and items_budget table. Both of them are related as oneToMany and manyToOne, by the id and material fields:
Material.orm.yml:
oneToMany:
itemsBudget:
targetEntity: ItemsBudget
mappedBy: material
ItemsBudget.orm.yml:
material:
targetEntity: Material
inversedBy: itemsBudget
joinColumn:
name: material
referencedColumnName: id
Here, the ItemsBudgetType where I set the material field as a collection:
$builder->add('budget', 'entity', array(
'class' => 'PanelBundle:Budget',
'attr' => array(
'class' => 'form-control',
),
))
->add('material', 'collection', array(
'type' => new MaterialType(),
'allow_add' => true
))
->add('quantity', 'number', array(
'attr' => array(
'class' => 'form-control',
),
))
->add('price', 'money', array(
'attr' => array(
'class' => 'form-control',
),
));
Just for information, the MaterialType:
$builder->add('name', 'text', array(
'attr' => array(
'class' => 'form-control',
),
))
->add('description', 'text', array(
'attr' => array(
'class' => 'form-control',
),
))
->add('current_quantity', 'text', array(
'attr' => array(
'class' => 'form-control',
'required' => false
),
))
->add('price', 'money', array(
'attr' => array(
'class' => 'form-control',
),
));
Here the index.html.twig of my ItemsBudget view:
<strong>Materiais</strong>
<div class="form-group">
<ul class="materials" data-prototype="{{ form_widget(form.material.vars.prototype)|e }}">
{% for material in form.material %}
<li>{{ form_widget(form.material.vars.prototype.name) }}</li>
{% endfor %}
</ul>
</div>
In the view, I have tried also as it is in the example: {{ form_row(material.name) }}, but it still shows the whole Material form.
And where I'm calling them, in the ItemsBudgetController:
public function addAction(Request $request)
{
$form = $this->createForm(new ItemsBudgetType(), new ItemsBudget());
$manager = $this->getDoctrine()->getManager();
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isValid()) {
$ItemsBudgetEntity = $form->getData();
$manager->persist($ItemsBudgetEntity);
$manager->flush();
$BudgetEntity = $form->get('budget')->getData();
$BudgetEntity->addItemsBudget($ItemsBudgetEntity);
$manager->persist($BudgetEntity);
$manager->flush();
$this->addFlash('success', 'Materiais para o orçamento adicionados');
return $this->redirect($this->generateUrl('panel_budgets'));
}
}
return $this->render('PanelBundle:ItemsBudget:index.html.twig', array(
'form' => $form->createView(),
'budgets' => $manager->getRepository('PanelBundle:Budget')->findAll()
));
}
The JavaScript is the same from the example too:
function addMaterial($collectionHolder, $newLinkLi) {
var prototype = $collectionHolder.data('prototype');
var index = $collectionHolder.data('index');
var newForm = prototype.replace(/__name__/g, index);
$collectionHolder.data('index', index + 1);
var $newFormLi = $('<li></li>').append(newForm);
$newLinkLi.before($newFormLi);
}
var $collectionHolder;
var addMaterialLink = $('Mais');
var $newLinkLi = $('<li></li>').append(addMaterialLink);
jQuery(document).ready(function () {
$collectionHolder = $('ul.materials');
$collectionHolder.append($newLinkLi);
$collectionHolder.data('index', $collectionHolder.find(':input').length);
addMaterialLink.on('click', function (e) {
e.preventDefault();
addMaterial($collectionHolder, $newLinkLi);
});
});
This is the issue: instead of showing only the name field from Material form, it is showing the whole form every time I click the "Mais". Am I missing something?
The javascript takes the content of the data-prototype attribute and appends it to the html of the form. The attribute in your template contains {{ form_widget(form.material.vars.prototype)|e }} which is the html prototype of the form.
Try:
<ul class="materials" data-prototype="{{ form_widget(form.material.vars.prototype.name) }}">
i have tried various ways, but i cant get form to come back isValid() so i wanted to make sure i have this portion correct first.
<?php
namespace ABC\DeBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller,
Sensio\Bundle\FrameworkExtraBundle\Configuration\Route,
Sensio\Bundle\FrameworkExtraBundle\Configuration\Template,
Sensio\Bundle\FrameworkExtraBundle\Configuration\Method,
Symfony\Component\HttpFoundation\Request,
Symfony\Component\HttpKernel\Exception\HttpException,
Symfony\Component\Form\FormBuilderInterface,
Symfony\Component\Form\Forms,
Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationExtension,
Symfony\Component\Form\Extension\Validator\ValidatorExtension,
Symfony\Component\Validator\Validation,
Symfony\Component\Validator\Constraints\Length,
Symfony\Component\Validator\Constraints\NotBlank,
Symfony\Component\Config\Definition\Exception\Exception,
Symfony\Component\HttpFoundation\Response,
ABC\CoreBundle\Controller\CoreController;
class DoSomethingController extends CoreController
{
protected $debug = FALSE;
public function doSomethingAction(Request $request)
{
/**
* build the form here
*
* Either use out custom build form object
* $form = $formFactory->createBuilder('form', $defaultData)
*
* Or alternatively, use the default formBuilder
* $form = $this->createFormBuilder($defaultData)
*/
$validator = Validation::createValidator();
$formFactory = Forms::createFormFactoryBuilder()
->addExtension(new HttpFoundationExtension())
->addExtension(new ValidatorExtension($validator))
->getFormFactory();
$defaultData = array(
'comment' => 'Type your comment here',
'name' => 'Type your name here',
'resources' => '{}',
'warning' => 'Warning, your still in debug mode on your controller.php'
);
//$form = $this->createFormBuilder($defaultData)
$form = $formFactory->createBuilder('form', $defaultData)
->setAction($this->generateUrl('do_something'))
->add("emails", 'text', array(
'label' => "Recipient's email address (separate with a comma)",
'constraints' => array(// constraints here
),
))
->add('comment', 'textarea', array(
'label' => "Leave a comment",
))
->add('name', 'text', array(
'label' => "Your name",
'constraints' => array(// constraints here
),
))
->add('email', 'email', array(
'label' => "Your email address",
'constraints' => array(// constraints here
),
))
->add('copy', 'checkbox', array(
'label' => "Send me a copy",
'required' => false,
))
->add('cancel', 'button', array(
'label' => "Cancel",
'attr' => array('class' => 'btn-branded'),
))
->add('save', 'submit', array(
'label' => "Email Resources",
'attr' => array('class' => 'btn-branded'),
));
//make resources visible by putting them into a text box
$resourceInputType = $this->debug ? 'text' : 'hidden';
$form->add('resources', $resourceInputType, array(
'constraints' => array(// constraints here
),
));
//add a visible warning input box, so we know were on debug, we don't want this released to live on debug.
$this->debug ? ($form = $form->add('warning', 'text')) : null;
$form .= $form->getForm();
//alternatively
//$form->bind($_POST[$form->getName()]);
//$form->handleRequest($request);
//validate
if ($form->isValid()) {
$data = $form->getData();
//run some data checks, then fire it off
$something = $this->DoSomething($data);
return $something;
//$return=array("responseCode"=>200, "data"=>$data);
// $return=json_encode($return); //json encode the array
// return new Response($return,200,array('Content-Type'=>'application/json'));//make sure it has the correct content type
}else
{
echo '<pre>';
var_dump('form is coming back as not isValid(), make sure debug is off, heres our errors list:<br>');
var_dump($form->getErrorsAsString());
echo '</pre>';
}
//its not a POST, or POST is invalid, so display the form
return $this->render($this->someTemplate, array(
'form' => $form->createView(),
));
}
}
1) Im a bit confused (oop wise) on the way to pass around this form object during conditional manipulation. Do i need to concatenate it when manipulating it or what does symfony offer to avoid this, or am i just passing the object around wrong? see this example to understand better this question. e.g. $form .= $form->getForm(); How would i properly concatenate this form object during manipulation, like i did when i used the ternary, to convine myself that when i pass this object around, its teh same object, and not a new one.
2) see any other problems that might be causing the breakage?
EDIT #Chausser
this is the latest code, streamlined a bit, that i am working with now using some apparently rare exmples found here http://api.symfony.com/2.5/Symfony/Component/Form/Forms.html. its still not coming back isValid() . Please compare my former, and new usage example of the form object.
<?php
/**
* #param Request $request
* #Route("/do/something", name="do_something", options={"expose"=true})
* #Method({"GET", "POST"})
* #return mixed
*/
public function doSomethingAction(Request $request)
{
$defaultData = array(
'comment' => 'Type your comment here',
'name' => 'Type your name here',
'resources' => '{}',
'warning' => 'Warning, your still in debug mode on your controller.php'
);
$resourceInputType = $this->debug ? 'text' : 'hidden';
$formFactory = Forms::createFormFactory();
$form = $formFactory
->createBuilder()
->setAction($this->generateUrl('do_something'))
->add("emails", 'text', array(
'label' => "Recipient's email address (separate with a comma)",
'constraints' => array(// constraints here
),
))
->add('comment', 'textarea', array(
'label' => "Leave a comment",
))
->add('name', 'text', array(
'label' => "Your name",
'constraints' => array(// constraints here
),
))
->add('email', 'email', array(
'label' => "Your email address",
'constraints' => array(// constraints here
),
))
->add('copy', 'checkbox', array(
'label' => "Send me a copy",
'required' => false,
))
->add('cancel', 'button', array(
'label' => "Cancel",
'attr' => array('class' => 'btn-branded'),
))
->add('save', 'submit', array(
'label' => "Email Resources",
'attr' => array('class' => 'btn-branded'),
))
->add('resources', $resourceInputType, array(
'constraints' => array(// constraints here
),
))
->getForm();
$form->handleRequest($request);
//validate
if ($form->isValid()) {
$data = $form->getData();
//run some data checks, then fire it off
$something = $this->DoSomething($data);
return $something;
//other options for returning
//$return=array("responseCode"=>200, "data"=>$data);
// $return=json_encode($something); //json encode the array
// return new Response($return,200,array('Content-Type'=>'application/json'));//make sure it has the correct content type
} else {
echo '<pre>';
var_dump('form is coming back as not isValid(), make sure debug is off, heres our errors list:<br>');
var_dump($form->getErrorsAsString());
echo '</pre>';
}
//its not a POST, or POST is invalid, so display the form
return $this->render($this->someTemplate, array(
'form' => $form->createView(),
));
}
EDIT
so now after my edits to get the form to not try and haldne the request, unless its teh POST request, not the GET request
if($request && $request->getMethod() == 'POST'){
$form->handleRequest($request);
//validate
if ($form->isValid()) {
$data = $form->getData();
//run some data checks, then fire it off
$something = $this->DoSomething($data);
return $something;
//other options for returning
//$return=array("responseCode"=>200, "data"=>$data);
// $return=json_encode($something); //json encode the array
// return new Response($return,200,array('Content-Type'=>'application/json'));//make sure it has the correct content type
} else {
echo '<pre>';
var_dump('form is coming back as not isValid(), make sure debug is off, heres our errors list:<br>');
var_dump($form->getErrorsAsString());
echo '</pre>';
}
}
which has led to the controller error mentioned below
Ok, it looks as if the validator extension, when used, was breaking, since the HttpFoundationExtension() wasnt being included. Apparently to use either the validator, or the factory builder (not sure which) it needs this extension as well.
working example, copied from initial example, with working parts added.
<?php
namespace ABC\DeBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller,
Sensio\Bundle\FrameworkExtraBundle\Configuration\Route,
Sensio\Bundle\FrameworkExtraBundle\Configuration\Template,
Sensio\Bundle\FrameworkExtraBundle\Configuration\Method,
Symfony\Component\HttpFoundation\Request,
Symfony\Component\HttpKernel\Exception\HttpException,
Symfony\Component\Form\FormBuilderInterface,
Symfony\Component\Form\Forms,
Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationExtension,
Symfony\Component\Form\Extension\Validator\ValidatorExtension,
Symfony\Component\Validator\Validation,
Symfony\Component\Validator\Constraints\Length,
Symfony\Component\Validator\Constraints\NotBlank,
Symfony\Component\Config\Definition\Exception\Exception,
Symfony\Component\HttpFoundation\Response,
ABC\CoreBundle\Controller\CoreController;
class DoSomethingController extends CoreController
{
protected $debug = FALSE;
public function doSomethingAction(Request $request)
{
$validator = Validation::createValidator();
$builder = Forms::createFormFactoryBuilder()
->addExtension(new ValidatorExtension($validator))
->addExtension(new HttpFoundationExtension());
$defaultData = array(
'comment' => 'Type your comment here',
'name' => 'Type your name here',
'resources' => '{}',
'warning' => 'Warning, your still in debug mode on your controller.php'
);
$resourcesInputType = $this->debug ? 'text' : 'hidden';
$form = $builder->getFormFactory()
->createBuilder('form', $defaultData)
->setAction($this->generateUrl('do_something'))
->add("emails", 'text', array(
'label' => "Recipient's email address (separate with a comma)",
'constraints' => array(// constraints here
),
))
->add('comment', 'textarea', array(
'label' => "Leave a comment",
))
->add('name', 'text', array(
'label' => "Your name",
'constraints' => array(// constraints here
),
))
->add('email', 'email', array(
'label' => "Your email address",
'constraints' => array(// constraints here
),
))
->add('copy', 'checkbox', array(
'label' => "Send me a copy",
'required' => false,
))
->add('cancel', 'button', array(
'label' => "Cancel",
'attr' => array('class' => 'btn-branded'),
))
->add('save', 'submit', array(
'label' => "Email Resources",
'attr' => array('class' => 'btn-branded'),
))->add('resources', $resourcesInputType, array(
'constraints' => array( // constraints here
),
))
->getForm()
->handleRequest($request);
if ($form->isValid()) {
$data = $form->getData();
//run some data checks, then fire it off
$something = $this->DoSomething($data);
return $something;
}
// initial render
return $this->render($this->someTemplate, array(
'form' => $form->createView(),
));
}
}
I am creating a magento custom admin module and a form. I want update this form but not updating. In Controller, under SaveAction() I print $this->getRequest()->getPost() and get empty array. please help me. Below code for form declination..
protected function _prepareForm() {
$form = new Varien_Data_Form(array(
'id' => 'edit_form1',
'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post',
'enctype' => 'multipart/form-data'
)
);
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
And Create a from filed set like
protected function _prepareForm() {
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('qbanner_form', array('legend' => Mage::helper('qbanner')->__('Art information')));
$fieldset->addField('name', 'text', array(
'label' => Mage::helper('catalog')->__('Product'),
'required' => false,
'name' => 'name',
));
$fieldset->addField('artist_name', 'text', array(
'label' => Mage::helper('catalog')->__('Artist Name'),
// 'name' => 'artist_name',
'value' => Mage::helper('catalog')->__('Art Name value'),
));
$fieldset->addField('bca_status', 'select', array(
'label' => Mage::helper('catalog')->__('Art status'),
'name' => 'bca_status',
'values' =>$this->_getAttributeOptions('bca_status'),
));
$fieldset->addField('reason', 'editor', array(
'name' => 'reason',
'label' => Mage::helper('catalog')->__('Reason'),
'title' => Mage::helper('catalog')->__('Reason'),
'style' => 'width:440px; height:300px;',
'wysiwyg' => true,
'required' => false,
));
$fieldset->addField('thumbnail', 'text', array(
'label' => Mage::helper('catalog')->__('Art status'),
'name' => 'thumbnail',
//'values' =>$this->_getAttributeOptions('thumbnail'),
//'renderer' => 'Qaz_Qbanner_Block_Adminhtml_Qbanner_Grid_Renderer_Image'
));
if (Mage::getSingleton('adminhtml/session')->getQbannerData()) {
$form->setValues(Mage::getSingleton('adminhtml/session')->getQbannerData());
Mage::getSingleton('adminhtml/session')->setQbannerData(null);
} elseif (Mage::registry('qbanner_data')) {
$form->setValues(Mage::registry('qbanner_data')->getData());
}
return parent::_prepareForm();
}
protected function _getAttributeOptions($attribute_code)
{
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', $attribute_code);
$options = array();
foreach( $attribute->getSource()->getAllOptions(true, true) as $option ) {
$options[$option['value']] = $option['label'];
}
return $options;
}
Here my
SaveAction()
public function saveAction() {
echo print_r( $this->getRequest()->getPost());
}
I have tied verious post. Any ideas?
Common error for all. You just need to add form key to your form.
Just add this line below your form declaration.
<input type="hidden" name="form_key" value="<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>" />
Like this
<form action="<?php echo Mage::helper("adminhtml")->getUrl("demo/adminhtml_demo/demo");?>" method="post" id="custom-payment-form" enctype="multipart/form-data">
<input type="hidden" name="form_key" value="<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>" />
Add this. Now you can get parameters by $this->getRequest()->getPost().
you can get variable of post and get method in magento with $this->getRequest()->getParams(); getParams() method But if you want to get exactly some variable data then use getParam('id');
/magento/catalog/product/view/id/406/category/14
$this->getRequest()->getParam('id') // 406
$this->getRequest()->getParams(); //get all get and post variables
In My form i use this code
$form->add('user', 'entity',
array(
'label' => 'User Name',
'class' => 'DotArtBundle:User',
'property' => 'name',
'query_builder' => function(EntityRepository $er){
return $er->createQueryBuilder('u')->where('u.type = 1');
}
)
);
I want
if user role is ROLE_ADMIN run this code and show all user (This code do this)
if user role is ROLE_USER this code only show authenticated user in list
'query_builder' => function(EntityRepository $er){
return $er->createQueryBuilder('u')->where('u.type = 1 and u.id = ' . $this->getUser()->getId());
}
Error
I check this code and return error:
$where = 'u.id = '.$userid;
$form = $this->createFormBuilder($poduct)
->add('user', 'entity',
array(
'label' => 'نانم کاربری',
'class' => 'DotArtBundle:User',
'property' => 'name',
'query_builder' => function(EntityRepository $er){
return $er->createQueryBuilder('u')->where($where);
}
)
)
Notice: Undefined variable: where in C:\xampp\htdocs\ArtGirl\src\Dot\ArtBundle\Controller\ProductController.php line 38
Solution:
$where = '';
$userid = $this->getUser()->getId();
if (!$this->get('security.context')->isGranted('ROLE_ADMIN')){
$where = ' and u.id = ' . $userid;
}
$form->add('user', 'entity',
array(
'label' => 'نانم کاربری',
'class' => 'DotArtBundle:User',
'property' => 'name',
'query_builder' => function(EntityRepository $er) use ($where){
return $er->createQueryBuilder('u')->where('u.type = 1 '.$where);
}
)
)
Im new to Zend framework, i would like to know how to add a date picker jquery widget to a zend_form I googled extensively but could not find anything precise
Kindly help me out. Thanks in advance!
Following is my Zend_form code
Form code
<?php
class Application_Form_Matriregistrationform extends Zend_Form
{
public $elementDecorators = array(
'ViewHelper',
'Errors',
array(array('data' => 'HtmlTag'), array('tag' => 'td', 'class' => 'element')),
array('Label', array('tag' => 'td')),
array(array('row' => 'HtmlTag'), array('tag' => 'tr')),
);
public $buttonDecorators = array(
'ViewHelper',
array(array('data' => 'HtmlTag'), array('tag' => 'td', 'class' => 'element')),
array(array('label' => 'HtmlTag'), array('tag' => 'td', 'placement' => 'prepend')),
array(array('row' => 'HtmlTag'), array('tag' => 'tr')),
);
public function init()
{
$this->setAction('/matri/public/matri/matri')
->setMethod('post');
$id = $this->addElement('hidden', 'id', array(
'decorators' => $this->elementDecorators,
));
$email = new Zend_Form_Element_Text('username');
$email->setLabel('Username')
->addFilter('StringToLower')
->setRequired(true)
->addValidator('NotEmpty', true)
->addValidator('EmailAddress')
->setDecorators($this->elementDecorators);
$this->addElement($email);
$password = new Zend_Form_Element_Password('password');
$password->setLabel('Password:')
->setRequired(true)
->setDecorators($this->elementDecorators);
$this->addElement($password);
$confpassword = new Zend_Form_Element_Password('confpassword');
$confpassword->setLabel('Confirm Password:')
->setRequired(true)
->setDecorators($this->elementDecorators)
->addValidator(new Zend_Validate_Identical($_POST['password']));
$this->addElement($confpassword);
$name = $this->addElement('text', 'firstname', array(
'decorators' => $this->elementDecorators,
'label' => 'Name:',
));
$this->addElement('datePicker','movie_release_date', array(
'label' => 'Release Date:',
'required'=> false
)
);
$gender2 = new Zend_Form_Element_Radio('gender');
$gender2->setSeparator('')
->setLabel('Gender:')
->setRequired(true)
->addMultiOption('m', 'Male')
->addMultiOption('f', 'Female')
->setDecorators($this->elementDecorators);
$this->addElement($gender2);
$DOB = $this->addElement('text', 'DOB', array(
'decorators' => $this->elementDecorators,
'label' =>'Date of Birth:',
));
$religion = $this->addElement('text', 'religion', array(
'decorators' => $this->elementDecorators,
'label' =>'Religion:',
));
$mothertongue = $this->addElement('text', 'mothertongue', array(
'decorators' => $this->elementDecorators,
'label' =>'Mother Tongue:',
));
$country = $this->addElement('text', 'country', array(
'decorators' => $this->elementDecorators,
'label' =>'Country:',
));
$maritalstatus = $this->addElement('text', 'maritalstatus', array(
'decorators' => $this->elementDecorators,
'label' =>'Marital Status:',
));
$height = $this->addElement('text', 'height', array(
'decorators' => $this->elementDecorators,
'label' =>'Height:',
));
$caste = $this->addElement('text', 'caste', array(
'decorators' => $this->elementDecorators,
'label' =>'Caste:',
));
$smoke = $this->addElement('text', 'smoke', array(
'decorators' => $this->elementDecorators,
'label' =>'Smoke:',
));
$smoke = new Zend_Form_Element_Radio('smoke');
$smoke->setSeparator('')
->setLabel('Smoke:')
->setRequired(true)
->addMultiOption('yes', 'Yes')
->addMultiOption('no', 'No')
->setDecorators($this->elementDecorators);
$this->addElement($smoke);
$drink = new Zend_Form_Element_Radio('drink');
$drink->setSeparator('')
->setLabel('Drink:')
->setRequired(true)
->addMultiOption('yes', 'Yes')
->addMultiOption('no', 'No')
->setDecorators($this->elementDecorators);
$this->addElement($drink);
$diet = new Zend_Form_Element_Radio('diet');
$diet->setSeparator('')
->setLabel('diet:')
->setRequired(true)
->addMultiOption('yes', 'Yes')
->addMultiOption('no', 'No')
->setDecorators($this->elementDecorators);
$this->addElement($diet);
$country = $this->addElement('text', 'country', array(
'decorators' => $this->elementDecorators,
'label' =>'Country:',
));
$state = $this->addElement('text', 'state', array(
'decorators' => $this->elementDecorators,
'label' =>'State of Residence:',
));
$city = $this->addElement('text', 'city', array(
'decorators' => $this->elementDecorators,
'label' =>'City of Residence:',
));
$submit = new Zend_Form_Element_Submit('submit');
$submit->setAttrib('id', 'submitbutton')
->setDecorators($this->buttonDecorators);
$this->addElement($submit);
//$this->addElements(array($id, $username, $firstname, $lastname, $submit));
}
public function loadDefaultDecorators()
{
$this->setDecorators(array(
'FormElements',
array('HtmlTag', array('tag' => 'table')),
'Form',
));
}
}
Form action code
public function matriAction()
{
// $this->_helper->layout->disableLayout();
$form = new Application_Form_Matriregistrationform();
$form->submit->setLabel('Profile Registration');
if ($this->_request->isPost()) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) {
echo 'Form Successfully sumbitted!';
exit;
} else {
$form->populate($formData);
}
}
$this->view->form = $form;
}
One way would be to use ZendX_jQuery. The other way would be to do it manually as you would do it for any other form.
For the manual way you need to include jquery and jquery-ui in your HTML's head tag, e.g.
<?php echo $this->headLink()->appendStylesheet($this->baseUrl('/css/smoothness/jquery-ui-1.8.7.custom.css')); ?>
<?php echo $this->headScript()->appendFile($this->baseUrl('/js/jquery-1.4.4.min.js')); ?>
<?php echo $this->headScript()->appendFile($this->baseUrl('/js/jquery-ui-1.8.7.custom.min.js')); ?>
Then you could add the following JavaScript to your html:
$(document).ready(function () {
/* assuming that text input datePicker would have id='datePicker' */
$( "#datePicker" ).datepicker({ dateFormat: 'dd/mm/yy' });
});
First, however, I would recommend having look at ZendX_jQuery. The reason I provided an example of the manual way is that I haven't yet tried doing it using ZendX_jQuery.
If you want to use ZendX follow this easy steps:
Download the Full Zend Framework library, and copy Zendx from "extras" Folder to your library Folder.
Add this to your application.ini to use ZendX:
pluginPaths.ZendX_Application_Resource = "ZendX/Application/Resource"
To use JQuery UI, you can fetch it from google cdn by adding this lines to your application.ini
resources.jquery.version = 1.4.1
resources.jquery.ui_enable = true
resources.jquery.ui_version = 1.8.4
resources.jquery.stylesheet = "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/smoothness/jquery-ui.css"
And now just add an Datepicker inside your Zend Form Class:
$birthdate = new ZendX_JQuery_Form_Element_DatePicker('birthdate');
$birthdate->setLabel('Geburtsdatum:')
->setJQueryParam('dateFormat', 'dd.mm.yy')
->setJQueryParam('changeYear', 'true')
->setJqueryParam('changeMonth', 'true')
->setJqueryParam('regional', 'de')
->setJqueryParam('yearRange', "1980:2000")
->setDescription('dd.mm.yyyy')
->addValidator(new Zend_Validate_Date(
array(
'format' => 'dd.mm.yyyy',
)))
->setRequired(true);
$this->addElement($birthdate);
$this->addElement('datePicker','movie_release_date', array(
'label' => 'Release Date:',
'required'=> false,
'class' => 'datepicker'
)
);
You need to add a class to the datePicker field in order for jquery to hook up to it. I'm not sure if my example above is correct as I usually use the following setAttrib method as follows.
$datePicker = new Zend_Form_Element_Text('datePicker');
$datePicker->setAttrib('class', 'datePicker')
->setRequired( true );