Symfony2 autocomplete form bundle - forms

I use this bundle: GenemuFormBundle
I install it due to all information on this site.
But it still dont work.
Here is my type form:
$builder
->add('PermitsCompany', 'genemu_jqueryautocompleter_entity', array(
'route_name' => 'ajax_company',
'class' => 'MainCoreBundle:Company',
'property'=>'name'
))
;
Here is my routing:
ajax_company:
defaults: { _controller: MainAdminBundle:Permits:ajaxCompany}
pattern: /ajax_company/
type: annotation
And here is my controller:
/**
* #Route("/ajax_company", name="ajax_company")
*/
public function ajaxCompanyAction(Request $request)
{
$permits = $this->getDoctrine()->getRepository('MainCoreBundle:Company')->findAll();
$json = array();
foreach ($permits as $permit) {
$json[] = array(
'label' => $permit->getName(),
'value' => $permit->getId()
);
}
$response = new Response(json_encode($json));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
I have no idea what I am doing wrong. I have no error. But autocomplete did not work.
When i go to route /ajax_company/ i can see values from data base like here:
[{"property":"Company 1","value":1},{"property":"Company 2","value":2},{"Company":"Company 3","value":3},{"property":"Company 4","value":4}]
Did I add forget something in twig? I have only form_widget

Try including form_javascript or form_stylesheet, in your twig template.
From https://github.com/genemu/GenemuFormBundle#template:
Template
You use GenemuFormBundle and you seen that it does not work! Maybe you
have forgotten form_javascript or form_stylesheet.
The principle is to separate the javascript, stylesheet and html. This
allows better integration of web pages.

Related

How to make a Symfony GET form redirect to route with parameter?

I want to create a form for searching a profile by username which redirect then to the profile page of the user. Btw, I use Symfony 3.2.
I reckon the natural way for doing this would be a GET action form. It would even allow a customer to change the url directly with the good username to see its profile.
Here is the code of my controller :
ProfileController.php
//...
/** #Route("/profil/search", name="profil_search") */
public function searchAction() {
$builder = $this->createFormBuilder();
$builder
->setAction($this->generateUrl('profil_show'))
->setMethod('GET')
->add('username', SearchType::class, array('label' => 'Username : '))
->add('submit', SubmitType::class, array('label' => 'Search'));
$form = $builder->getForm();
return $this->render('profils/profil_search.html.twig', [
'form' => $form->createView(),
]);
}
/** #Route("/profil/show/{username}", name="profil_show") */
public function showAction($username) {
$repository = $this->getDoctrine()->getRepository('AppBundle:User');
$searchedUser = $repository->findOneByUsername($username);
return $this->render('profils/profil_show.html.twig', [
'searchedUser' => $searchedUser,
]);
}
//...
This code will lead to the following error message :
Some mandatory parameters are missing ("username") to generate a URL for
route "profil_show".
I read the documentation thoroughly but couldn't guess, how can I pass the username variable to the profil_show route as a parameter ?
If my way of doing is not the good one, thanks for telling me in comments but I'd still like to know how to use GET forms.
EDIT :
Thanks to #MEmerson answer, I get it now. So for future noobs like me, here is how I did it :
/** #Route("/profil/search", name="profil_search") */
public function searchAction(Request $request) {
$data = array();
$builder = $this->createFormBuilder($data);
$builder
//->setAction($this->generateUrl('profil_show'))
//->setMethod('GET')
->add('username', SearchType::class, array('label' => 'Username : '))
->add('submit', SubmitType::class, array('label' => 'Search'));
$form = $builder->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
return $this->redirectToRoute('profil_show', array('username' => $data["username"]));
}
return $this->render('profils/profil_search.html.twig', [
'method' => __METHOD__,
'form' => $form->createView(),
'message' => $message,
]);
}
If you take a look at the error message it says that the problem is where you are trying to generate the URL for the path 'profil_show'.
Your controller annotations require that the URL be populated with a user name
/** #Route("/profil/show/{username}", name="profil_show") */
this means that Symfony is expecting http://yoursite.com/profil/show/username for the route. But if you want to pass it as a GET form posting it really should be expecting http://yoursite.com/profil/show?username
you can add a second route or change your existing route to be
/** #Route("/profil/show", name="profil_show_search") */
that should solve your problem.

Pass the current querystring parameters through symfony forms

Our application uses several webforms and some of them only should add or change several parameters in the querystring. As example there are a filter form and a form for the list order (just a dropdown).
Both are indipendant, but if I change one, I have to pass the current querystring parameters with the new request. How can I manage it?
This is just one of the possible solutions, it will depend on your implementation if it would help you.
<?php
$allowedQueryParams = array('param1', 'param2', 'param3');
// I'll fake a request here
$request = new Request(array('param2' => 'foo', 'param3' => 'bar', 'param4' => 'dummy'));
$formFactory = Forms::createFormFactoryBuilder()->getFormFactory();
$formBuilder = $formFactory->createBuilder();
$formBuilder->add('param1', 'text');
$data = array();
foreach ($allowedQueryParams as $param) {
if ($request->query->has($param)) {
// Add the query param as hidden field to you form
$formBuilder->add($param, 'hidden');
$data[$param] = $request->query->get($param);
}
}
$formBuilder->setData($data);
$form = $formBuilder->getForm();
So basically you add hidden fields with the current query parameters.
Edit:
But if you would have many forms, you might want to do this with an EventSubscriber
An alternative approach would be to combine the two forms into one master form.
From your controller:
$formData = array(
'filterParams' => array(), // Default filter parameters
'listOrderParams' => array(), // Default list order parameters
);
$form = $this->createFormBuilder($task)
->add('filterParams', new FilterFormType())
->add('listOrderParams', new ListOrderFormType())
->add('update', 'submit')
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$formData = $form->getData();

Load Form from module into custom page template

I have successfully added my own form (from the same module) into my custom template, but now I wish to load the taxonomy add term form (used by ubercart I think for product categories in the catalog vocab) into my template.
I have gotten this far with my module - filename simpleadmin.module
/**
* #file
* A module to simplify the admin by replacing add/edit node pages
*/
function simpleadmin_menu() {
$items['admin/products/categories/add'] = array(
'title' => 'Add Category',
'page callback' => 'simpleadmin_category_add',
'access arguments' => array('access administration pages'),
'menu_name' => 'menu-store',
);
return $items;
}
function simpleadmin_category_add() {
module_load_include('inc', 'taxonomy', 'taxonomy.admin');
$output = drupal_get_form('taxonomy_form_term');
return theme('simpleadmin_category_add', array('categoryform' => $output));
}
function simpleadmin_theme() {
return array(
'simpleadmin_category_add' => array(
'template' => 'simpleadmin-template',
'variables' => array('categoryform' => NULL),
'render element' => 'form',
),
);
}
?>
And as for the theme file itself - filename simpleadmin-template.tpl.php, only very simple at the moment until I get the form to load into it:
<div>
This is the form template ABOVE the form
</div>
<?php
dpm($categoryform);
print drupal_render($categoryform);
?>
<div>
This is the form template BELOW the form
</div>
Its telling me that it is
Trying to get property of non-object in taxonomy_form_term()
and throwing up an error. Should I be using node_add() and passing the nodetype?
To render a taxonomy term form, the function should be able to know the vocabulary to which it belongs to. Otherwise how would it know which form to show? I think this is the proper way to do it.
module_load_include('inc', 'taxonomy', 'taxonomy.admin');
if ($vocabulary = taxonomy_vocabulary_machine_name_load('vocabulary_name')) {
$form = drupal_get_form('taxonomy_form_term', $vocabulary);
return theme('simpleadmin_category_add', array('categoryform' => $form));
}
To redirect your form use hook_form_alter
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
//get your vocabulary id or use print_r or dpm for proper validation
if($form_id == 'taxonomy_form_term' && $form['#vocabulary']['vid'] = '7' ){
$form['#submit'][] = 'onix_sections_form_submit';
}
}
function yourmodule_form_submit($form, &$form_state) {
$form_state['redirect'] = 'user';
}

Write hyperlink inside the Zend Form?

I am using Zend-Framework in my project. I made a login form using the Zend Form that contains the User Id and Passwords fields with a submit button. Everything is working fine in the login form.
How do I add two hyperlinks inside the login form that is one for the Sign-Up and other for the Forget Password?
I've faced the same problem before, and solved it by creating a custom Zend_Form_Element_Html, as follows:
class Zend_Form_Element_Html extends Zend_Form_Element_Xhtml {
/**
* Default form view helper to use for rendering
* #var string
*/
public $helper = 'formNote';
public function isValid($value, $context = null) {
return true;
}
}
So, in your form you just have to do the following:
$tag = new Zend_Form_Element_Html('forgetPassword');
$tag->setValue('Forgotten your password?');
$this->addElement($tag);
Hope this helps!
In your viewscript file where you print the form, e.g. login.phtml
echo $this->form;
you can specify any other html markup, e.g. links
echo "<p><a href='".$this->url ( array ('controller' => 'authentication',
'action' => 'lostPW' ) )."'>
Lost pw </a></p>";
So you actually do not write it in the form itself but in the view script where you echo the form.
Try this:
$passwordElement->setDescription('Forgot password?');
$passwordElement->getDecorator('Description')->setOption('escape', false);
Description decorator will add this text beside your field.
You can use Zend_Form_Decorator_ViewScript
Or, create a custom Zend_Form_Element to render HTML elements or ViewScript.
For only decorators use directly in the form try:
$this->addElement(new Zend_Form_Element_Note(array(
'name' => 'forgotten',
'value' => __('Forgot your password?'),
'decorators' => array(
array('ViewHelper'),
array('HtmlTag', array(
'tag' => 'a',
'href' => $this->getView()->url(array(
'remind'
))
)),
)
)), 'forgotten');

Zend form in a popup (fancybox, lightbox....)

I am developping a web application using Zend and I ran out of ideas for a problem I am having. In just a few words, I am trying to have a contact form in a popup (Fancybox, lightbox, colorbox or whatever...). The whole thing works fine, in the sense that it shows up the contact form in the popup and allows to send emails. However, whenever there are errors (unfilled input or filled wrong), I couldn't get those errors to be displayed on the popup (it actually redirects me back to the form in a normal display (view+layout), to show the errors.
It is perhaps possible but I now thought that perhaps I could more easily bring my error message to a new popup (the contact page, filled unproperly, would lead to a error popup page...). I think this alternative could look cool but am having real trouble doing it. Now my real question is : Can we really make a form on a popup, using Facybox (Lighbox or any other actually ... just want my popup) and Zend? Any Guru outhere??
Thanks a lot
here is the code:
the link for instance:
<a class="popLink" href=" <?php echo $this->url(array('module'=>'default', 'controller'=>'contact', 'action'=>'sendmail')).'?ProID='.$this->proProfil->getProID(); ?>">Contact</a>
the action:
public function sendmailAction()
{
$this->_helper->layout()->setLayout('blank');
$request = $this->getRequest();
$proID = $this->_getParam("ProID");
$professionalsList = new Model_DirPro();
$proName = $professionalsList->getProInfo($proID);
$translate = Zend_Registry::get('translate');
Zend_Validate_Abstract::setDefaultTranslator($translate);
Zend_Form::setDefaultTranslator($translate);
$contactform = new Form_ContactForm();
$contactform->setTranslator($translate);
$contactform->setAttrib('id', 'contact');
$this->view->contactform = $contactform;
$this->view->proName = $proName;
if ($request->isPost()){
if ($contactform->isValid($this->_getAllParams())){
$mailSubject = $contactform->getValue('mailsubject');
if ($contactform->mailattcht->isUploaded()) {
$contactform->mailattcht->receive();
//etc....
the form:
class Form_ContactForm extends Zend_Form
{
public function init ()
{
$this->setName("email");
$this->setMethod('post');
$this->addElement('text', 'mailsubject',
array('filters' => array('StringTrim'),
'validators' => array(), 'required' => true, 'label' => 'Subject:'));
$mailattcht = new Zend_Form_Element_File('mailattcht');
$mailattcht->setLabel('Attach File:')->setDestination(APPLICATION_PATH.'/../public/mails');
$mailattcht->addValidator('Count', false, 1);
$mailattcht->addValidator('Size', false, 8000000);
$mailattcht->addValidator('Extension', false,
'jpg,png,gif,ppt,pptx,doc,docx,xls,xslx,pdf');
$this->addElement($mailattcht, 'mailattcht');
$this->addElement('textarea', 'mailbody',
array('filters' => array('StringTrim'),
'validators' => array(), 'required' => true, 'label' => 'Body:'));
$this->addElement('submit', 'send',
array('required' => false, 'ignore' => true, 'label' => 'Send'));
$this->addElement('hidden', 'return', array(
'value' => Zend_Controller_Front::getInstance()->getRequest()->getRequestUri(),
));
$this->setAttrib('enctype', 'multipart/form-data');
}
}
I would suggest implementing AJAX validation. This would allow for the form to be verified before it is submitted. ZendCasts has a good tutorial on how to accomplish this: http://www.zendcasts.com/ajaxify-your-zend_form-validation-with-jquery/2010/04/
Ajax requests are handled via the contextSwitch action helper. You can to specify the various contexts an action needs to handle (xml or json) in the init method of the controller as follows:
public function init()
{
$this->_helper->contextSwitch()
->addActionContext('send-mail', 'json')
->initContext()
;
}
The request url should contain a "format=json" appended to the query string. This will execute the action and send the response in json format. The default behaviour of JSON context is to extract all the public properties of the view and encode them as JSON. Further details can be found here http://framework.zend.com/manual/en/zend.controller.actionhelpers.html
I found a "probably not the prettiest" working solution, it is to indeed use ajax as mentioned in the previous zendcast for validation to stop the real validation (preventdefault), process the data return the result and if everything's ok restart it.