Symfony forms or normal HTML forms - forms

I am using Symfony 1.4 to create project, and i need to create dynamic forms depending upon the question set type coming from database. i have used Symfony forms in rest of my project, but in this case using symfony forms seems to be tough, as i need dynamic form.
can it be safe to use normal HTML forms..in symfony project, or it is advisable to use Symfony forms. so need your help.

You can use html forms, but it would bypass symfony's form validation system.
You can still build dynamic forms by creating and adding input widgets to the current form, or a new form inside an action. You can then echo the form in the template and the dynamically generated fields will be part of the form as well.
If you start with a MyForm.class.php in the lib/forms, make sure to add:
$this->validatorSchema->setOption('allow_extra_fields', true);
Otherwise, you will automatically get validation errors. If you want to add fields to a form in an action you would do something like this:
$this->form = new MyForm();
$widgetSchema = $this->form->getWidgetSchema();
$widgetSchema['add_field'] = new sfWidgetFormInputText();
When you echo your form the 'add_field' input will be added to it.

It would help to have more information about what you're doing, but here's one way in which forms can be dynamic in Symfony. This code creates widgets and validators for a survey dynamically based on the "type" of a question:
class SurveyAnswerForm extends BaseSurveyAnswerForm
{
public function configure()
{
$question = $this->object->Question;
$method = sprintf('createWidgetAndValidatorFor%sInputType', $question->type);
$this->$method($question);
$this->getWidget('value')->setOption('label', $question->question);
$this->getValidator('value')->setOption('required', $question->required);
}
protected function createWidgetAndValidatorForTextFieldInputType(Question $question)
{
$this->setWidget('value', new sfWidgetFormInputText());
$this->setValidator('value', new sfValidatorString());
}
protected function createWidgetAndValidatorForTextAreaInputType(Question $question)
{
$this->setWidget('value', new wfWidgetFormTextareaAutosize());
$this->setValidator('value', new sfValidatorString());
}
//etc. for as many types as you require
}
Note: while this answer is code from one of my projects, it was heavily influenced by this answer over on SymfonyExperts.

Related

Joomla: how can I use one form for frontend and backend view?

I am creating a Joomla 2.5 component. In the backend I created a model/view/controller 'Members' which shows a grid. I also created an MVC 'Member' which is used to add or edit a member from the grid. So far so good.
Now, I would like to add a frontend view that is very similar to the 'Member' view in the backend, but this one is meant for visitors so they can subscribe themselves. It has to look more user friendly than the backend form, so I will create a slightly different 'Member' view in the frontend, but I would really like to reuse the form file (/administrator/components/mycomponent/models/forms/member.xml) from the backend!
So, my question is how my frontend view can find and use that backend form?
You definitely have to load it in the model. Your model has to extend JModelAdmin and then the getForm function has to load the form
public function getForm($data = array(), $loadData = true) {
// Get the form.
JForm::addFormPath(JPATH_COMPONENT_ADMINISTRATOR . '/models/forms');
JForm::addFieldPath(JPATH_COMPONENT_ADMINISTRATOR . '/models/fields');
$form = $this->loadForm('com_dpattachments.attachment', 'attachment', array('control' => 'jform', 'load_data' => $loadData));
if (empty($form)) {
return false;
}
....
}
I'm using the same approach in my DPAttachments component, it is for Joomla 3.1 but the main code, to use the same model and form on the front and back, should also run on Joomla 2.5. Here is the link to the getForm function
https://github.com/Digital-Peak/DPAttachments/blob/master/com_dpattachments/admin/models/attachment.php#L102
If you are following Joomla MVC guidance your frontend should be able to pick-up the forms automatically.
In your view (though it should request it from the model actually) you can write:
$formsPath = JPATH_ADMINISTRATOR.DS.'components'.DS.'com_mycom'.DS.'models'.DS.'forms';
$this->form = JForm::getInstance('myform', $formsPath.DS.'myform.xml');
You can also look at the summer of code cm_config project which pulls the config forms and the templateDetails form to the front end using JSON. https://github.com/Buddhima/joomla-cms/tree/gsoc_com_config or the com_services branch.

What alternatives are there to Yii active form?

I wish to build a form that does not create/update any active records. An example of such a form would be a search filter using check boxes for the user to select which categories to apply to the search.
Everything I read about forms in Yii is centred around the CActiveForm class. What is the Yii way to build forms that don't use active records?
If you want to embrace Yii's convenient form handling, you should use CActiveForm. It does not require CActiveRecord. But it always requires a model for your form data - which is a good thing, because this will keep the validation rules out of your view files. Instead of a CActiveRecord you could also build a simple model class from CFormModel.
class SomeForm extends CFormModel
{
public $name;
public $email;
public function rules()
{
return array(
array('name,email','required'),
array('email','email'),
);
}
}
Check the docs of the CHtml class. While it contains all the active* method, there are plain form methods in there as well, such as checkBox() or checkBoxList() that sound like what you're looking for.

Symfony 2.x Form Field Name

When I render a form, form Filed Name is given as an array. For example: search[item], search[keyword] etc. where search is name of the form.
I'm not great on working with forms but I think, the name should be rendered as simply, name="item" or name="keyword".
I've looked at all the documentation, customizing form rendering topic etc. but I can't find any way to change the default behaviour of Symfony form to render form filed name from 'search[item]' to 'item'.
This way, when I ask for the POST data, I can ask simply $this->getRequest()->request->get('item'), as I have to deal with lots of individual parameters.
Help would be great i) To figure out how to achieve what I want. ii) to let me know, why the name is rendered this way. is this the good practice?
Rather than accessing parameters from the Request object, you can bind the Request object to the form.
For example, in your controller method that you post your form to:
namespace Acme\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Acme\Form\MyFormClass;
class MyFormController extends Controller
{
receiveFormAction(Request $request)
{
$form = new MyFormClass();
// you can specify that a route only accepts a post
// request in the routing definition
if ($request->isMethod('POST')) {
// this populates the form object with the data
// from the form submission
$form->bind($request);
if ( ! $form->isValid()) {
throw new \Exception('Invalid form');
}
// an array of the data the format you require
$data = $form->getData();
$data['item'];
$data['keyword'];
// etc.
}
}
}
The above is the way you should be handling forms in Symfony 2, and is how you can leverage the power that the forms component gives you, with validation etc.
Symfony supports multiple forms on a page. They might be instances of the same form or have similar field names. Having the fields for each form all together in an array makes this easy to do.

How can I use the sfValidatorEmail validator in Symfony to validate a single email field

I have a form with 2 elements that will be submitted and then update part of a user profile.
I don't want to use the entire generated form and have to remove all the fields except for the two I need. I just want to be able to create a quite simple form to do my update.
Is there a way to utilize Symfony's sfValidatorEmail inside the action on the returned value of an email field?
Since the regex is already written in the validator, I would like to reuse it, but I don't know how to use it in the action after the non-symfony form has been submitted.
Two approaches here - you could construct a simple form anyway extending from sfForm/sfFormSymfony (doesn't have to be ORM-based) that just contains the 2 fields you want. That way you can use the existing validation framework, and then use $myForm->getValues() after everything has been validated to get your values for your profile update.
Alternatively, as you've mentioned, you can use the sfValidatorEmail class in your action like so:
$dirtyValue = "broken.email.address"
$v = new sfValidatorEmail();
try
{
$v->clean($dirtyValue);
}
catch (sfValidatorError $e)
{
// Validation failed
}
The latter approach quickly leads to messy code if you have many values that need cleaning, and it's worth putting the logic back into a form to handle this in the usual manner.
If you're submitting a form with 2 elements, it should be a form on the edit and update end, period. Symfony forms are lightweight, there's no performance reason to not use them. Instead, make a custom form for this purpose:
class ProfileUpdateForm extends ProfileForm
{
public function configure()
{
$this->useFields(array('email', 'other_field'));
}
}

Loading models in Zend_Form using Zend Framework

I'm trying to build a form using the Zend_Form component, but the number of elements varies. The information for each Zend_Form element is stored in a database (name, options, validators, filters, etc.).
The application I'm working on consists of building surveys which contain a varying number of questions. Each question is associated with different arrays of answers. Ultimately my goal is to build arrays of radio/checkbox buttons, dynamically, server-side.
I'm looking for a pretty way to generate my form, but I'm not sure of the best way to load the model within the form. Should the model be loaded in the controller then passed (somehow, via a parameter?) directly to the form, or is it better to load the model within the Form init() method? Where's the best place to put the logic, should it be within the form class, or within the controller, or within the model?
My idea is to fetch form element properties (name, rules, filters, etc.) in the database, then iterate and finally render the form. What do you think of this approach? Ultimately, elements will be dynamically added (client-side), this time, using AJAX and a JavaScript library (such as jQuery).
Here are a couple useful links I found via Google, but I think they all answer a slightly different question than mine:
On building dynamic forms, server side:
http://framework.zend.com/wiki/display/ZFPROP/Zend_Form+generation+from+models+-+Jani+Hartikainen
http://weierophinney.net/matthew/archives/200-Using-Zend_Form-in-Your-Models.html
http://codeutopia.net/blog/2009/01/07/another-idea-for-using-models-with-forms/
On building dynamic forms, client side, with AJAX processing:
http://www.jeremykendall.net/2009/01/19/dynamically-adding-elements-to-zend-form/
I think I found a possible solution, it involves passing an array of Zend Form elements to the Zend Form::__construct() method. The constructor takes an array of options, one of them is called "elements". Have a look at the source code within the Zend Framework library.
I coded a new private method within the controller, called buildSurveyForm(). Note : the object, passed as a parameter, is built from a huge SQL query with half a dozen JOIN statements, fetching data from a few tables (surveys, questions, answers, etc.) within the database. One of the public attributes for this class consists of an array of questions, stored as objects (with public methods/attributes as well, etc.). Same for answers. The code for building these classes is pretty trivial and out of topic here.
Here's the code within the survey controller. I copy/pasted and edited/dropped a few lines to make it a lot clearer :
private function buildSurveyForm(MyApp_Object_Survey $survey)
{
foreach ($survey->questions as $question)
{
$element = new Zend_Form_Element_MultiCheckbox($question->order);
$element->addMultiOptions($question->getAnswersLabels());
$element->setName($question->order);
$element->setLabel($question->title);
$elements[] = $element;
}
// Here's the trick :
$formOptions = array('elements' => $elements);
$surveyForm = new MyApp_Survey_Form($formOptions);
$urlHelper = $this->_helper->getHelper('url');
$surveyForm->setAction($urlHelper->url(array(
'controller' => 'survey',
'action' => 'vote'),
'default'
));
$surveyForm->setMethod('post');
$this->_forms['survey'] = $surveyForm;
return $this->_forms['survey'];
}
The MyApp Survey Form class only contains a Submit button within the init() method. The dynamically generated elements with the code above are added BEFORE this submit button (which is unexpected, but useful). This class simply extends Zend_Form.
Then, within survey controller / view action :
public function viewAction()
{
$surveyModel = $this->_model['survey'];
$survey = $surveyModel->getFullSurvey($this->_getParam('id'));
$survey = new MyApp_Object_Survey($survey);
// Calls above private method :
$surveyForm = $this->buildSurveyForm($survey);
$this->view->assign(array(
'surveyForm' => $surveyForm,
));
}
Adding filters, validators and decorators to form elements is now trivial. My proposal is a bit dirty, but I think it gets the job done. I will add a new proposal if I find something more elegant. Feel free to post different answers/solutions.
You could extend Zend_Form.
Zend form is not good place for logic, only form representation.
So, Load all needed elements using model in controller and pass them to the form in contructor as parameters.