Symfony2 setDefaultOptions(OptionsResolverInterface $resolver) - forms

I am quite new in Symfony2. I am trying to develop a website where someone can register/login. So to i am trying to make the register form but it always thows exception regarding the setDefaultOptions(OptionsResolverInterface $resolver) method.
RegisterType.php:
<?php
namespace MyappBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class RegisterType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options){
$builder
->add('name', TextType::class, array(
'label' => 'Your Name',
'label_attr' => array(
'attr' => array(
'class' => 'control-label'
)
),
'attr' => array(
'class' => 'form-control'
)
))
->add('email', EmailType::class, array(
'label' => 'Your Email',
'label_attr' => array(
'attr' => array(
'class' => 'control-label'
)
),
'attr' => array(
'class' => 'form-control'
)
))
->add('password',RepeatedType::class, array(
'type' => PasswordType::class, array(
'first_options' => array(
'label' => 'Your Password', array(
'label_attr' => array(
'attr' =>array(
'class'=> 'control-label'
)
)
),
'attr' => array(
'class' => 'form-control'
)
),
'second_options' => array(
'label' => 'Repeat Password', array(
'label_attr' => array(
'attr' =>array(
'class'=> 'control-label'
)
)
),
'attr' => array(
'class' => 'form-control'
)
)
)))
->add('tel', NumberType::class, array(
'label' => 'Your Telephone number',
'label_attr' => array(
'attr' => array(
'class' => 'control-label'
)
),
'attr' => array(
'class' => 'form-control'
)
))
->add('register', 'submit', array(
'attr' => array(
'class' => 'btn btn-default'
)
));
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(['data_class' => 'MyappBundle\Entity\Users']);
}
public function getName(){
return 'register';
}
}
RegisterControler.php
<?php
namespace MyappBundle\Controller;
use MyappBundle\Form\Type\RegisterType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use MyappBundle\Entity\Users;
use Symfony\Component\HttpFoundation\Request;
class RegisterController extends Controller
{
public function indexAction(Request $request)
{
$user = new Users();
$form = $this->createForm(new RegisterType($user), array(
'action' => $this->generateUrl('myapp_register'),
'method' => 'POST'
));
if($form->isSubmitted() && $form->isValid()){
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return $this->redirect($this->generateUrl('myapp_homepage'));
}
return $this->render('MyappBundle:Default:register.html.twig', array('form' => $form->createView(),));
}
}
The Error that I get is:
CRITICAL - Uncaught PHP Exception Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException: "The option "0" does not exist. Defined options are: "action", "allow_extra_fields", "attr", "auto_initialize", "block_name", "by_reference", "cascade_validation", "compound", "constraints", "csrf_field_name", "csrf_message", "csrf_protection", "csrf_provider", "csrf_token_id", "csrf_token_manager", "data", "data_class", "disabled", "empty_data", "error_bubbling", "error_mapping", "extra_fields_message", "first_name", "first_options", "inherit_data", "intention", "invalid_message", "invalid_message_parameters", "label", "label_attr", "label_format", "mapped", "max_length", "method", "options", "pattern", "post_max_size_message", "property_path", "read_only", "required", "second_name", "second_options", "translation_domain", "trim", "type", "validation_groups", "virtual"." at C:\Users\Vicky\Documents\My Documents\PROJECTS\VF-HOUSING_SYMFONY\vendor\symfony\symfony\src\Symfony\Component\OptionsResolver\OptionsResolver.php line 760
Can anyone please help me?

I always use the configureOptions method to map my entity to the form. So try this:
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(
array(
'data_class' => 'MyappBundle\Entity\Users',
)
);
}

So the problem was solved.
Deleting the following function in RegisterType.php
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(
array(
'data_class' => 'MyappBundle\Entity\Users',
)
);
}
and modifying the RegisterControler.php as follows
$user = new User();
$form = $this->createForm(RegisterType::class,$user);
$form->handleRequest($request);
it solves the problem that I mentioned.
Thank you for your help!

Related

Add form error to a repeated FormType in Controller

I'm trying to add an error to a mail field of type repeated:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('lastname', 'text', array(
'required' => true,
'trim' => true,
'max_length' => 255,
'attr' => array('placeholder' => 'lastname',
)
))
->add('mail', 'repeated', array(
'type' => 'email',
'label' => 'email',
'invalid_message' => 'Les Emails doivent correspondre',
'options' => array('required' => true),
'first_options' => array('label' => 'email',
'attr' => array('placeholder' => 'ph_mail_first',
)),
'second_options' => array('label' => 'emailvalidation',
'attr' => array('placeholder' => 'ph_mail_second',
'requiered' => true
)),
'required' => true,
'trim' => true
))
}
public function getName()
{
return 'AddUser';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'csrf_protection' => true,
));
}
And this what I'm doing in my controller:
$sMessage = $this->container->get('translator')->trans('error');
$oForm->get('mail')->addError(new \Symfony\Component\Form\FormError($sMessage));
This method is working with the other fields except for this one, the error message does not appear. I also tried with
get('mail.first') and get('mail.first_options')
This works fine:
$sMessage = $this->container->get('translator')->trans('error');
$oForm->get('lastname')->addError(new \Symfony\Component\Form\FormError($sMessage));
I managed to find a workaround. I honestlty don't know if this is the right solution but it can help someone stuck with this problem.
$oForm['mail']['first']->addError(new \Symfony\Component\Form\FormError($sMessage));
$oForm->get('mail')->get('first')

Prestashop HelperFrom/List - messy layout

I'm new to prestashop and I worked the whole day on creating a back office interface that allows the user to write, edit, and delete articles. It is sort of a blog. I used Prestashop's Helpers (Form and List) and everything works great. I also added a new tab in the back office to access this tool.
The problem is that the layout is messy and doesn't look like the other forms and listing pages. The layout is really not sexy. Maybe I should look at some css file, or add any function in my controller ? You'll find the source code of the latter here (I can't insert images, not enough reputation --'):
<?php
class Article extends ObjectModel
{
/** #var string Name */
public $id_article;
public $titre;
public $contenu;
public $url_photo;
/**
* #see ObjectModel::$definition
*/
public static $definition = array(
'table' => 'article',
'primary' => 'id_article',
'fields' => array(
'titre' => array(
'type' => self::TYPE_STRING,
'validate' => 'isGenericName',
'required' => true,
'class' => 'lg'
),
'contenu' => array(
'type' => self::TYPE_STRING,
'validate' => 'isGenericName',
'required' => true
),
'url_photo' => array(
'type' => self::TYPE_STRING,
'validate' => 'isGenericName',
'required' => false,
),
),
);
}
class AdminBlogController extends AdminController{
public function initContent(){
parent::initContent();
}
public function __construct(){
$this->table = 'article';
$this->className = 'Article';
$this->lang = false;
// Building the list of records stored within the "article" table
$this->fields_list = array(
'id_article' => array(
'title' => 'ID',
'align' => 'center',
'width' => 25
),
'titre' => array(
'title' => 'Titre',
'width' => 'auto'
),
'contenu' => array(
'title' => 'Contenu',
'width' => 'auto'
)
);
// This adds a multiple deletion button
$this->bulk_actions = array(
'delete' => array(
'text' => $this->l('Delete selected'),
'confirm' => $this->l('Delete selected items?')
)
);
parent::__construct();
}
// This method generates the list of results
public function renderList(){
// Adds an Edit button for each result
$this->addRowAction('edit');
// Adds a Delete button for each result
$this->addRowAction('delete');
return parent::renderList();
}
// This method generates the Add/Edit form
public function renderForm(){
// Building the Add/Edit form
$this->fields_form = array(
'tinymce' => true,
'legend' => array(
'title' => 'Article'
),
'input' => array(
array(
'type' => 'text',
'label' => 'Titre',
'name' => 'titre',
'class' => 'lg',
'required' => true,
//'desc' => 'Nom de l\'article',
),
array(
'type' => 'textarea',
'label' => 'Contenu',
'name' => 'contenu',
'class' => 'lg',
'required' => true,
'autoload_rte' => true,
//'desc' => 'Contenu de l\'article',
),
array(
'type' => 'file',
'label' => 'Photo',
'name' => 'url_photo',
'class' => 'lg',
'required' => true,
//'desc' => 'Contenu de l\'article',
)
),
'submit' => array(
'title' => $this->l('Save'),
'class' => 'button'
)
);
return parent::renderForm();
}
}
?>
Thank you.
I just needed to set $this->bootstrap = true

Zf2 - Doctrine Hydrator Fieldset

I'm new with ZendFramework and Doctrine 2.
I try to implement a form with fieldset and Doctrine Hydrator.
The form and validators work good, but not Hydrator.
My source code:
AuthController.php
public function signupAction()
{
$userForm = new UserForm($this->getServiceLocator()->get('Doctrine\ORM\EntityManager'));
$request = $this->getRequest();
if ($request->isPost()) {
var_dump($request->getPost());
$userForm->setData($request->getPost());
if ($userForm->isValid()) {
$user = $userForm->getData();
var_dump($user);
}
}
return new ViewModel(array(
'form' => $userForm,
));
}
UserForm.php
class UserForm extends Form
{
public function __construct($em) {
parent::__construct('User');
$this->setAttribute('method', 'post')
->setHydrator(new DoctrineObject($em, 'User\Entity\User'));
$this->add(array(
'type' => 'User\Form\Fieldset\UserFieldset',
'options' => array(
'use_as_base_fieldset' => true
)
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Send'
)
));
}
}
UserFieldset.php
class UserFieldset extends Fieldset implements InputFilterProviderInterface, ObjectManagerAwareInterface
{
/**
* #var ObjectManager
*/
private $objectManager;
public function __construct()
{
parent::__construct('User');
// Id
$this->add(array(
'name' => 'id',
'type' => 'Zend\Form\Element\Hidden',
));
// FirstName
$this->add(array(
'name' => 'firstName',
'attributes' => array(
'required' => 'required',
),
'options' => array(
'label' => 'Prénom',
),
'type' => 'Zend\Form\Element\Text',
));
}
public function getInputFilterSpecification()
{
return array(
'firstName' => array(
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 2,
'max' => 100,
'messages' => array(
\Zend\Validator\StringLength::TOO_LONG => 'Le prénom est trop long (maximum %max% caractères)',
\Zend\Validator\StringLength::TOO_SHORT => 'Le prénom est trop court (minimum %min% caractères)',
),
),
),
),
),
'id' => array(
'required' => false,
),
);
}
public function setOption($key, $value) { }
/**
* Set the object manager
*
* #param ObjectManager $objectManager
*/
public function setObjectManager(ObjectManager $objectManager)
{
$this->objectManager = $objectManager;
}
/**
* Get the object manager
*
* #return ObjectManager
*/
public function getObjectManager()
{
return $this->getObjectManager();
}
}
I have not a User object, but a array...
A idea?
Thanks you!
Aurélien

Translate zend framework 1 form labels and error message

I have a web site which is in English and Arabic. I converted the text into Arabic but the form labels and error message is not converting. I am using gettext adapter and how do i convert this labels. I am using Zend_Form and creating object of this form and passign this to view.
Bootstrap file
protected function _initTranslate() {
$translate = new Zend_Translate('gettext', APPLICATION_PATH . "/lang/", null, array('scan' => Zend_Translate::LOCALE_DIRECTORY));
$registry = Zend_Registry::getInstance();
$registry->set('Zend_Translate', $translate);
//Zend_Form::setDefaultTranslator($translate);
$translate->setLocale('ar');
}
public function _initRoutes() {
$this->bootstrap('FrontController');
$this->_frontController = $this->getResource('FrontController');
$router = $this->_frontController->getRouter();
$langRoute = new Zend_Controller_Router_Route(
':lang', array(
'lang' => 'ar',
'module' => 'default',
'controller' => 'index',
'action' => 'index'
), array(
'lang' => 'en|ar'
)
);
$defaultRoute = new Zend_Controller_Router_Route(
':controller/:action', array(
'module' => 'default',
'controller' => 'index',
'action' => 'index'
)
);
$defaultRoute = $langRoute->chain($defaultRoute);
$router->addRoute('langRoute', $langRoute);
$router->addRoute('defaultRoute', $defaultRoute);
}
protected function _initLanguage() {
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new My_Controller_Plugin_Language());
}
Form
class Application_Form_Contactus extends Zend_Form {
public function init() {
// Set the method for the display form to POST
$this->setMethod('post');
$this->addElement('text', 'name', array('label' => 'Name', 'class' => 'inputbox',
'filters' => array('StringTrim'),
'required' => true));
// Add an email element
$this->addElement('text', 'email', array('label' => 'Email', 'class' => 'inputbox',
'required' => true, 'filters' => array('StringTrim'), 'validators' => array('EmailAddress')));
$this->addElement('submit', 'submit', array(
'required' => false,
'label' => 'Send',
'value' => 'save',
'class' => 'submit-but',
'attribs' => array('type' => 'submit'),
));
}
}
Controller
$form = new Application_Form_Contactus();
$form->setAction($this->view->getSiteUrl() . 'Contactus');
$translate = Zend_Registry::get('Zend_Translate');
$form->element->setTranslator($translate);
$this->view->form = $form;
view
echo $this->form;
Try to attach to the Zend_Form object as a global translator. This will also translate validation error messages :
Zend_Form::setDefaultTranslator($translate);
Or you can do this :
Zend_Validate_Abstract::setDefaultTranslator($translator);
Please see zend form i18n
Try to set default translator.
Zend_Form::setDefaultTranslator($translate);
One more alternate way could be:
$form = new Application_Form_Contactus();
$translate = Zend_Registry::get('Zend_Translate');
foreach ($form->getElements() as $key => $element) {
$element->setTranslator($translate);
}

ZF2 form as array

I'd like to create a simple zend form with a few fields but i wanna collect this fields into an array. I'd like to see my form names like this:
name="login[username]" name="login[password]" name="login[submit]"
I wasn't able to find any description. If somebody knows the solution please let me know!
You can try with fieldsets like that
namespace Application\Form;
use Application\Entity\Brand;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
class YourFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct()
{
parent::__construct('login');
$this->add(array(
'name' => 'username',
'options' => array(
'label' => 'Username'
),
'attributes' => array(
'required' => 'required'
)
));
$this->add(array(
'name' => 'password',
'type' => 'Zend\Form\Element\Password',
'options' => array(
'label' => 'Password'
),
'attributes' => array(
'required' => 'required'
)
));
$this->add(array(
'name' => 'submit',
'type' => 'Zend\Form\Element\Submit',
'options' => array(
'label' => 'Submit'
),
'attributes' => array(
'required' => 'required'
)
));
}
/**
* #return array
*/
public function getInputFilterSpecification()
{
return array(
'name' => array(
'required' => true,
)
);
}
}