I've a problem with Symfony.
I've a VideoController that renders a twig page.
This twig page includes another twig page that has a rendercontroller. With this render controller, the route crash and it says that the "video" variable that I send with the first controller doesn't exists. What's wrong?
This is the code for VideoController:
public function getVideo(Request $request, $id) {
$entityManager = $this->getDoctrine()->getManager();
$video = $entityManager->getRepository('AppBundle:Video')->getVidById($id);
return $this->render('vids/videos.html.twig', ['video' => $video]); //Needs improvements
}
videos.html.twig:
{% block main %}
<center>
<video controls style="width:720px;height:360px;" poster="poster.png">
<source src="{{ video.link }}" type="video/mp4;" codecs="avc1.42E01E, mp4a.40.2" />
</video>
{{ include ("comments/comment.html.twig") }}
</center>
{% endblock %}
comment.html.twig:
{% block comment %}
<br><br>
<center>
{{ render(controller('AppBundle:Video:commentVideo')) }}
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
</center>
{% endblock %}
CommentController:
class CommentsController extends Controller
{
/*
* Check if session is valid. If so, user can comment. SECURITY SYSTEM NEEDS TO BE DEVELOPED!!!
* #Route("/", name="comment")
* #Method({"GET", "POST"})
*/
public function commentVideoAction(Request $request) {
$comment = new Comment();
$form = $this->createFormBuilder($comment)
->add('text', TextType::class)
->add('Invia Commento', SubmitType::class)
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$comment = $form->getData();
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($comment);
$entityManager->flush();
return $this->render('vids/videos.html.twig');
}
return $this->render('vids/videos.html.twig', array(
'form' => $form->createView(),
));
}
}
In your render (commentVideoAction), you have the twig file "vids/videos.html.twig" and you don't pass the video variable. I think you use the bad template. (
I think there s a mistake in your VideoController.
Try with public function getVideoAction(Request $request, $id) instead of just getVideo
And your structure is bad, you have a loop in your controllers, try like this:
videos.html.twig:
{% block main %}
<center>
<video controls style="width:720px;height:360px;" poster="poster.png">
<source src="{{ video.link }}" type="video/mp4;" codecs="avc1.42E01E, mp4a.40.2" />
</video>
{{ render(controller('AppBundle:Video:commentVideo')) }}
</center>
{% endblock %}
comment.html.twig:
{% block comment %}
<br><br>
<center>
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
</center>
{% endblock %}
CommentController:
class CommentsController extends Controller
{
/*
* Check if session is valid. If so, user can comment. SECURITY SYSTEM NEEDS TO BE DEVELOPED!!!
* #Route("/", name="comment")
* #Method({"GET", "POST"})
*/
public function commentVideoAction(Request $request) {
$comment = new Comment();
$form = $this->createFormBuilder($comment)
->add('text', TextType::class)
->add('Invia Commento', SubmitType::class)
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$comment = $form->getData();
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($comment);
$entityManager->flush();
return $this->render('vids/videos.html.twig');
}
return $this->render('vids/comment.html.twig', array(
'form' => $form->createView(),
));
}
}
Related
In Easy Admin, I already have a list/edit form of users. I want to add an extra form to change password of any member user. (password, repeat password, submit)
In the documentation custom forms are told to be entity specific. For example, to create a custom product form, you create a custom controller:
easy_admin:
entities:
# ...
Product:
controller: AppBundle\Controller\ProductController
# ...
But this solution doesn't fit to my problem. I already set a user form and use that form.
I can set an event listener and manage saving the password but I'm stuck with adding this simple form.
Firstly, you need a controller to handle requests associated with your users (create one if you don't have it already)
/**
* #Route("/user/change-password", name="change_password")
*/
public function changePassword(Request $request, UserPasswordEncoderInterface $passwordEncoder)
{
$changePasswordModel = new ChangePassword();
$form = $this->createForm(ChangePasswordType::class, $changePasswordModel);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$user = $entityManager->find(User::class, $this->getUser()->getId());
$user->setPassword(
$passwordEncoder->encodePassword(
$user,
$form->get('newPassword')->getData()
)
);
$entityManager->persist($user);
$entityManager->flush();
return $this->redirect('/?entity=User&action=show&id='. $this->getUser()->getId());
}
return $this->render('admin/theme/changePassword/change_password.html.twig', array(
'changePasswordForm' => $form->createView(),
));
}
Then I created a form type that looks like this:
class ChangePasswordType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('oldPassword', PasswordType::class, [
'required' => true,
'label' => 'Type your current password',
])
->add('newPassword', RepeatedType::class, [
'type' => PasswordType::class,
'invalid_message' => 'Passwords do not match.',
'first_options' => ['label' => 'Type your new password'],
'second_options' => ['label' => 'Retype your new password']
]);
}
public function setDefaultOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => ChangePassword::class,
));
}
public function getName()
{
return 'change_passwd';
}
}
I created a form model with custom validation, you can edit this however you like
class ChangePassword
{
/**
* #SecurityAssert\UserPassword(
* message = "Wrong value for your current password!"
* )
*/
public $oldPassword;
/**
* #Assert\Length(
* min = 6,
* minMessage = "Password must be at least 6 characters long!"
* )
*/
public $newPassword;
}
Lastly, extend your base twig with someting like this
{% extends 'base.html.twig' %}
{% block title %}Change password
{% endblock %}
{% block stylesheets %}
{{ parent() }}
{{ encore_entry_link_tags('change-password') }}
{% endblock %}
{% block body %}
{{ parent() }}
<body id="{% block body_id %}{% endblock %}">
<div class="container-fluid h-100">
<div class="row justify-content-center align-items-center h-100">
<div class="col col-sm-8 col-md-8 col-lg-6 col-xl-4">
{{ form_start(changePasswordForm, {'attr':{'class':'form-signin'}}) }}
{{ form_row(changePasswordForm.oldPassword, {'attr': {'class':'form-control mb-2'} }) }}
{{ form_row(changePasswordForm.newPassword.first, {'attr': {'class':'form-control mb-2'} }) }}
{{ form_row(changePasswordForm.newPassword.second, {'attr': {'class':'form-control mb-2'} }) }}
<button class="btn btn-dark btn-lg btn-block mt-3" type="submit">Change password</button>
{{ form_end(changePasswordForm) }}
</div>
</div>
</div>
</body>
{% endblock %}
{% block javascripts %}
{{ encore_entry_script_tags('change-password') }}
{% endblock %}
I created a button on my show user action that takes you to /user/change-password and that is pretty much it.
So I have this simple form:
class CreditType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('credits', EntityType::class, [
'class' => Product::class,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('product')
->orderBy('product.amount');
},
'expanded' => true,
'choice_label' => function ($key) {
return $key->amount.' credits voor maar '.$key->price;
}
]);
}
}
which I use in the following Controller:
public function credits(Request $request)
{
$form = $this->createForm(CreditType::class);
$form->handleRequest($request);
if ($form->isSubmitted()) {
throw new \Exception('It works!');
}
return $this->render(
'credits/credits_widget.html.twig',
[
'form' => $form->createView(),
]
);
}
And use this in my XXX.html.twig
{{ render(controller('App\\Controller\\DetailsController:credits')) }}
I have been working with symfony for 4 weeks now so not that long.
I want to call some functions when the form is submitted only nothing that I place in the if statement is working, it doesn't throw any exception at the moment. Am I not seeing something or is it not possible to do this when I render a form?
EDIT:
my credits_widget.html.twig
{% block credits %}
{{ form_start(form.credits) }}
{{ form_widget(form.credits) }}
{% if app.user %}
<button type="submit">Koop nu!</button>
{% else %}
<button type="button">Login en koop</button>
<button type="button">Registreer en koop</button>
{% endif %}
{{ form_end(form.credits) }}
{% endblock %}
The problem is that the form is rendered without action and when submitted, it is submitted by default to the root route from which it was rendered. So the credits action is not being called. You should change the action of the form like this:
public function credits(Request $request)
{
// set current url path as form's action
$form = $this->createForm(CreditType::class, null, , [
'action' => $request->getRequestUri()
]);
$form->handleRequest($request);
if ($form->isSubmitted()) {
throw new \Exception('It works!');
}
return $this->render(
'credits/credits_widget.html.twig',
[
'form' => $form->createView(),
]
);
}
EDIT: You are currently rendering subform form.credits when you should really render form as it is passed from your controller. Your credits_widget.html.twig template should look like this:
{% block credits %}
{{ form_start(form) }}
{{ form_widget(form) }}
{% if app.user %}
<button type="submit">Koop nu!</button>
{% else %}
<button type="button">Login en koop</button>
<button type="button">Registreer en koop</button>
{% endif %}
{{ form_end(form) }}
{% endblock %}
I'm building a Symfony application and when I work on it, it is too slow. I have wondering what can cause this so I went in the profiler timeline to see what is going on but I was amazed that all those classes have very big data 10 MB, 22 MB and so on. See the picture:
This is my Object bundle. The yellow is my own class with my twigs. I do not understand what is this delay and what is this big data.... Can someone explain to me what is going on and how can be optimized this because on a production if it is like now it is too slow... Total time 3962 ms
Here is the controller - nothing fancy generate from the console with minor changes:
<?php
namespace George\ObjectsBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use George\ObjectsBundle\Entity\Object;
use George\ObjectsBundle\Form\ObjectType;
/**
* Object controller.
*
* #Route("/admin/object")
*/
class ObjectController extends Controller
{
/**
* Lists all Object entities.
*
* #Route("/", name="object")
* #Method("GET")
* #Template()
*/
public function indexAction(Request $request)
{
$session = $request->getSession();
$locale = $request->getLocale();
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('ObjectsBundle:Object')->findAll();
// echo $locale;
/*
$category = new Object();
$category->translate('bg')->setTitle('Chaussures');
$category->translate('en')->setTitle('Shoes');
$category->translate('bg')->setDescription('Chaussures');
$category->translate('en')->setDescription('Shoes');
$category->translate('bg')->setAddress('Chaussures');
$category->translate('en')->setAddress('Shoes');
$category->setMode('a');
$category->setLat('12');
$category->setLongt('12');
echo $category->translate('bg')->getTitle();
$category->mergeNewTranslations(); $em->persist($category);
$em->flush();
*/
return array(
'entities' => $entities,
);
}
/**
* Creates a new Object entity.
*
* #Route("/", name="object_create")
* #Method("POST")
* #Template("ObjectsBundle:Object:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new Object();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('object'));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a form to create a Object entity.
*
* #param Object $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Object $entity)
{
$form = $this->createForm(new ObjectType(), $entity, array(
'action' => $this->generateUrl('object_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new Object entity.
*
* #Route("/new", name="object_new")
* #Method("GET")
* #Template()
*/
public function newAction()
{
$entity = new Object();
$form = $this->createCreateForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Finds and displays a Object entity.
*
* #Route("/{id}", name="object_show")
* #Method("GET")
* #Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ObjectsBundle:Object')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Object entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Displays a form to edit an existing Object entity.
*
* #Route("/{id}/edit", name="object_edit")
* #Method("GET")
* #Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ObjectsBundle:Object')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Object entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Creates a form to edit a Object entity.
*
* #param Object $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Object $entity)
{
$form = $this->createForm(new ObjectType(), $entity, array(
'action' => $this->generateUrl('object_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing Object entity.
*
* #Route("/{id}", name="object_update")
* #Method("PUT")
* #Template("ObjectsBundle:Object:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ObjectsBundle:Object')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Object entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('object_edit', array('id' => $id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a Object entity.
*
* #Route("/{id}", name="object_delete")
* #Method("DELETE")
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ObjectsBundle:Object')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Object entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('object'));
}
/**
* Creates a form to delete a Object entity by id.
*
* #param mixed $id The entity id
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('object_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm();
}
}
The main twig for the admin:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% block title -%}<title>Admin</title>{% endblock %}
{% block stylesheets %}
{% stylesheets
'#CoreBundle/Resources/public/css/*' %}
<link href="{{ asset(asset_url) }}" rel="stylesheet">
{% endstylesheets %}
{% endblock %}
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
</head>
<body>
{% block menu -%} {% endblock %}
{% block body -%} {% endblock %}
{% block javascripts -%}
{% javascripts
'#CoreBundle/Resources/public/js/jquery-1.11.3.min.js'
'#CoreBundle/Resources/public/js/bootstrap.min.js'
'#CoreBundle/Resources/public/js/fine-uploader.min.js'
'#CoreBundle/Resources/public/js/jquery-ui.min.js'
'#CoreBundle/Resources/public/js/datatables.min.js'
'#CoreBundle/Resources/public/js/Buttons-1.1.0/js/dataTables.buttons.min.js'
'#CoreBundle/Resources/public/js/Buttons-1.1.0/js/buttons.html5.js'
'#CoreBundle/Resources/public/js/Buttons-1.1.0/js/buttons.bootstrap.min.js'
'#CoreBundle/Resources/public/js/JSZip-2.5.0/jszip.min.js'
'#CoreBundle/Resources/public/js/RowReorder-1.1.0/js/dataTables.rowReorder.min.js'
%}
<script src="{{ asset(asset_url) }}" type="text/javascript"></script>
{% endjavascripts %}
{% endblock %}
{% block readyjs -%}
{{ tinymce_init() }}
<script type="text/javascript" >
function post_order ( ord, url)
{
$.ajax({
method: "POST",
url: url,
data: { elem: ord }
})
.done(function( msg ) {
// alert( msg );
});
}
$(document).ready(function () {
var optionsDatatables = {
dom: 'Bfrtip',
buttons: [
'copyHtml5', 'excelHtml5', 'csvHtml5'
]
}
if($('#dattab').hasClass('allow-order'))
{
//if we want more properties
// optionsDatatables.rowReorder = {
//selector: 'tr',
// update: true,
// dataSrc: '.ord-id'
// }
optionsDatatables.rowReorder = true;
}
var table = $('#dattab').DataTable(optionsDatatables);
var order;
if($('#dattab').hasClass('allow-order')) {
$('#dattab').on('draw.dt', function () {
var rows = table.rows().data();
var ord = new Array();
for (var i = 0, ien = rows.length; i < ien; i++) {
ord[i] = rows[i].DT_RowId;
}
order = ord;
$('#save_sort').fadeIn();
});
}
$('#save_sort').click(function(){
console.log(order);
post_order(order,$('#dattab').data('url'));
$(this).fadeOut();
});
});
</script>
{% endblock %}
</body>
</html>
The index which extends the base
{% extends "CoreBundle::admin_inner.html.twig" %}
{% block body -%}
<div class="container">
<div class="row">
<div class="col-xs-12">
{#{{ app.request.locale }}#}
<h1>Object list</h1>
{% for locale in ['en', 'bg'] %}
<li>
<a href="{{ path(app.request.get('_route'), app.request.get('_route_params')| merge({'_locale' : locale})) }}">
{{ locale }}
</a>
</li>
{% endfor %}
{{ app.session.get('_locale') }}{#
{{ app.request.locale }}#}
<div class="table-responsive">
<table class="table table-hover table-bordered" id="dattab">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
<th>Mode</th>
<th>Lat</th>
<th>Longt</th>
<th>Address</th>
<th>Created</th>
<th>Updated</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for entity in entities %}
<tr>
<td>{{ loop.index }}</td>
<td>{{ entity.translate(app.session.get('_locale')).title }} </td>
<td>{{ entity.translate(app.session.get('_locale')).description }} </td>
<td>{{ entity.mode }}</td>
<td>{{ entity.lat }}</td>
<td>{{ entity.longt }}</td>
<td>{{ entity.translate(app.session.get('_locale')).address }}</td>
<td>{% if entity.created %}{{ entity.created|date('Y-m-d H:i:s') }}{% endif %}</td>
<td>{% if entity.updated %}{{ entity.updated|date('Y-m-d H:i:s') }}{% endif %}</td>
<td>
<a href="{{ path('object_edit', { 'id': entity.id }) }}"
class="btn btn-primary"> <span class="glyphicon glyphicon-edit"
aria-hidden="true"></span> Edit</a>
<a href="{{ path('admin_floor', { 'id': entity.id }) }}"
class="btn btn-info"> <span class="glyphicon glyphicon-edit"
aria-hidden="true"></span> Floors</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<ul>
<li>
<a href="{{ path('object_new') }}">
Create a new entry
</a>
</li>
</ul>
</div>
</div>
</div>
{% endblock %}
And the inner with the menu:
{% extends "CoreBundle::admin_base.html.twig" %}
{% block menu %}
{{ include('CoreBundle::menu.html.twig') }}
{% endblock %}
I would first check whether all your frontend resources are loading correctly (scripts, images, css).
This can considerably slow down you app.
You can check it in firebug or developer console.
I'm new with Symfony2. I have page rapport and rapport/addnew and I am using the same form for both. What I need to do is to redirect to addnew when the user fill the form in rapport and click submit button.
Here is the function I am using in my DefaultController:
public function showListAction (Request $request)
{
$mission = $this->getDoctrine()
->getRepository('LRC203Bundle:Mission')
->findAll();
$form = $this->createForm(new RapportType(), $mission);
return $this->render('LRC203Bundle:Default:rapport.html.twig', array('form' => $form->createView(), 'mission' => $mission ));
}
and this is my html.twig:
{% block body %}
{% block missionsList %}
<ul>
{% for m in mission %}
<li> {{m.car}} </li>
<li> {{m.name}} </li>
{% endfor %}
</ul>
{% endblock %}
{% block newMission %}
{{ form(form) }}
{% endblock %}
{% endblock %}
Controller action
public function rapportAction(Request $request) {
$mission = new Mission();
$form = $this->createForm(new RapportType(), $mission);
$form->handleRequest($request);
if($form->isValid()) {
$em=$this->getDoctrine()->getManager();
$em->persist($mission); $em->flush();
}
return $this->render('LRC203Bundle:Default:rapport.html.twig',
array(
'form' => $form->createView()
)
);
}
RapportType
class RapportType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('car','text')
->add('name','text')
->add('save', 'submit');
}
public function getName() {
return 'rapport';
}
}
So all I need is to link the Submit button to addnew page.
So actually you are on the right track, you just need to add:
if($form->isValid()) {
$em=$this->getDoctrine()->getManager();
$em->persist($mission); $em->flush();
return $this->redirect($this->generateUrl('your_path'));
}
And this will do the trick.
if you want to redirect by controller try this
symfony adwise
you can try to how figure it out by "action" element of the form, like:
<form action="{{ path('task_new') }}" method="post" {{ form_enctype(form) }}>
{{ form_widget(form) }}
<input type="submit" />
</form>
or by this way
$form = $this->createFormBuilder($task)
->setAction($this->generateUrl('target_route'))
->setMethod('GET')
->add('task', 'text')
->add('dueDate', 'date')
->add('save', 'submit')
->getForm();
or
$form = $this->createForm(new FormType(), $obj, array( 'action' => 'whatever you need'));
and catch the response
Hello I want to create form and inserting record to mysql table on clicking on submit button in Symfony.
I am new in symfony. I have created form but it didn't response on submit. Here is my code
DefaultController.php
<?php
namespace Sym\FormBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sym\FormBundle\Entity\TblCust;
use Symfony\Component\HttpFoundation\Request;
use Sym\FormBundle\Form\TblCustType;
class DefaultController extends Controller
{
public function indexAction(Request $request)
{
$tbl = new TblCust();
// $form = $this->createForm(new TblCustType(),$tbl);
$form = $this->createFormBuilder($tbl)
->add('custName','text')
->add('custCity','text')
->add('custAddress','text')
->add('custPhno','text')
->add('save','submit')
->getForm();
$form->handleRequest($request);
if($form->isValid()){
$em = $this->getDoctrine()->getManager();
$em = persist('$tbl');
$em->flush();
return new response('New Customer Added..!');
}
$build['form']=$form->createView();
return $this->render('FormBundle:Default:index.html.twig',array( 'form' => $form->createView(),));
}
}
routing.yml
form_homepage:
pattern: /Form
defaults: { _controller: FormBundle:Default:index }
index.html.twig
{% block gender_widget %}
{% spaceless %}
{% if form %}
<ul {{ block('widget_container_attributes') }}>
{% for child in form %}
<li>
{{ form_widget(child) }}
{{ form_label(child) }}
</li>
{% endfor %}
</ul>
{% else %}
{# just let the choice widget render the select tag #}
{{ block('choice_widget') }}
{% endif %}
{% endspaceless %}
{% endblock %}
{% block container %}
{% endblock%}
I have created form using doctrine:generate:bundle symfony commend
TblCustType.php
<?php
namespace Sym\FormBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class TblCustType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('custName')
->add('custCity')
->add('custAddress')
->add('custPhno')
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Sym\FormBundle\Entity\TblCust'
));
}
/**
* #return string
*/
public function getName()
{
return 'sym_formbundle_tblcust';
}
}
My output is looking like below image
My problem is when i click on submit button it doesn't return response and i can not save my record. Please help my out this.
I believe you need to put the form tag in twig:
{{ form_start(form) }}
//all form widgets
//submit button
{{ form_rest(edit_form) }} <-- so it renders the hidden ones like the csrf token
</form>
You need to use form_start, form_rest and form_end like that :
{% block gender_widget %}
{% spaceless %}
{% if form %}
{{ form_start(form) }}
<ul {{ block('widget_container_attributes') }}>
{% for child in form %}
<li>
{{ form_widget(child) }}
{{ form_label(child) }}
</li>
{% endfor %}
</ul>
{{ form_rest(form) }}
{{ form_end(form) }}
{% else %}
{# just let the choice widget render the select tag #}
{{ block('choice_widget') }}
{% endif %}
{% endspaceless %}
{% endblock %}