I create an entity with self referencing. My entity look like this:
class Question
{
/**
* #ORM\OneToMany(targetEntity="Question", mappedBy="parent")
**/
private $children;
/**
* #ORM\ManyToOne(targetEntity="Question", inversedBy="children")
* #ORM\JoinColumn(name="parent_id", referencedColumnName="id")
**/
private $parent;
}
And i create a form to edit a Question. With this form i can add many childs to a Question. After i post this form i will save the childs for a parent Object. But the persisting of childs for a parent fails, nothing happens in the database.
public function manageDependencyAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$question = $em->getRepository('AppMyBundle:Question')->find($id);
if (!$question) {
$this->get('session')->getFlashBag()->add('danger', $this->get('translator')->trans('objectNotFound'));
return $this->redirect($this->generateUrl('app_question_list'));
}
$form = $this->createForm($this->get('form.type.question'), $question, array())->add('save', 'submit', array('label' => 'save', 'translation_domain' => 'messages', 'attr' => array('class' => 'btn btn-primary')));
$form->handleRequest($request);
if ($form->isValid()) {
// dump($question->getChildren()); // This is not empty. In this array are the selected childs.
$em->persist($question);
$em->flush();
}
}
change your entity methods:
public function addChild(Question $children)
{
$this->children[] = $children;
$children->setParent($this);
return $this;
}
Related
I'm currently working on something like a survey/quiz in Symfony. To do so, I have a Question-Entity with an Description, and a Quiz-Entity, which has nothing special unity know except of a submit date.
The important thing is that I want to generate a dynamic form with a random dataset of questions from the db. My current FormType looks like this:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {
$questions = $event->getData();
$form = $event->getForm();
$i = 0;
foreach($questions as $question) {
$form
->add('question'.$i, TextareaType::class,[
'label' => $question['description'],
'mapped' => false,
])
;
$i++;
}
$form->add('submit', SubmitType::class);
});
}
My controller:
/**
* #Route("/new", name="new")
*/
public function newQuiz(Request $request)
{
$result = $this->quizQuestionRepository->getRandomQuestion();
$form = $this->createForm(QuestionFormType::class, $result);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
dd($data);
}
return $this->render('question/new.html.twig', [
'form' => $form->createView()
]);
}
The Question-Entity:
/**
* #ORM\Entity()
* #ORM\Table(name="questions")
*/
class Question
{
/**
* #ORM\Id()
* #ORM\Column(type="uuid", unique=true)
*/
private string $id;
/**
* #ORM\Column(type="text")
*/
private string $description;
/**
* #ORM\Column(type="string")
*/
private string $category;
public function __construct()
{
$this->id = Uuid::uuid4()->toString();
}
// GETTERS AND SETTERS - NOTHING SPECIAL
}
But this doesn't work. For some reason, I get the questions objects returned, not the insertions from the textareas. Can someone help me out?
It's simple im doing a permission table from Companies and Users where i have to store the user id and the company id right now i have this and i get this error
Expected value of type "App\Entity\CompanyUserPermissionMap" for association field "App\Entity\User#$companyUserPermissionMaps", got "App\Entity\Company" instead.
User Entity
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $userId;
/**
* #ORM\Column(type="string", length=12)
*/
private $code;
/**
* #ORM\Column(type="string", length=180, unique=true)
*/
private $email;
/**
* #var CompanyUserPermissionMap[]
* #ORM\OneToMany(targetEntity="App\Entity\CompanyUserPermissionMap", mappedBy="user", orphanRemoval=true)
*/
private $companyUserPermissionMaps;
public function __construct()
{
$this->companyUserPermissionMaps = new ArrayCollection();
}
public function getCompanyUserPermissionMaps(): Collection
{
return $this->companyUserPermissionMaps;
}
public function addCompanyUserPermissionMaps(CompanyUserPermissionMaps $permission): self
{
if (!$this->companyUserPermissionMaps->contains($permission)) {
$this->companyUserPermissionMaps[] = $permission;
$permission->setUser($this);
}
return $this;
}
Company Entity
#########################
## PROPERTIES ##
#########################
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $companyId;
/**
* #ORM\Column(type="string", length=6, unique=true)
*/
private $code;
/**
* #var CompanyUserPermissionMap[]
* #ORM\OneToMany(targetEntity="App\Entity\CompanyUserPermissionMap", mappedBy="company", orphanRemoval=true)
*/
private $companyUserPermissionMaps;
public function __construct()
{
$this->companyUserPermissionMaps = new ArrayCollection();
}
/**
* #return Collection|CompanyUserPermissionMaps[]
*/
public function getCompanyUserPermissionMaps(): Collection
{
return $this->companyUserPermissionMaps;
}
public function addCompanyUserPermissionMaps(AccountingBankPermission $permission): self
{
if (!$this->companyUserPermissionMaps->contains($permission)) {
$this->companyUserPermissionMaps[] = $permission;
$permission->setAccount($this);
}
return $this;
}
public function removeCompanyUserPermissionMaps(AccountingBankPermission $permission): self
{
if ($this->companyUserPermissionMaps->contains($permission)) {
$this->companyUserPermissionMaps->removeElement($permission);
// set the owning side to null (unless already changed)
if ($permission->getAccount() === $this) {
$permission->setAccount(null);
}
}
return $this;
}
relation table
Column(type="integer")
private $companyUserPermissionId;
/**
* #var User
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="companyUserPermissionMaps")
* #ORM\JoinColumn(referencedColumnName="user_id", nullable=false)
*/
private $user;
/**
* #var Company
* #ORM\ManyToOne(targetEntity="App\Entity\Company", inversedBy="companyUserPermissionMaps")
* #ORM\JoinColumn(referencedColumnName="company_id", nullable=true)
*/
private $company;
/**
* #return int|null
*/
public function getCompanyUserPermissionId(): ?int
{
return $this->companyUserPermisionId;
}
/**
* #return User
*/
public function getUser(): ?User
{
return $this->user;
}
/**
* #param User $user
* #return AccountingBankPermission
*/
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
/**
* #return Company
*/
public function getCompany(): ?Company
{
return $this->company;
}
/**
* #param array $company
* #return CompanyUserPermissionMap
*/
public function setCompany(?array $company): self
{
$this->company = $company;
return $this;
}
Form type
$builder
->add('roles' ,ChoiceType::class ,[
'required' => true,
'choices' => $this->roles,
'multiple' => true,
'expanded' => true,
'label_attr' => [
'class' => 'custom-control-label',
],
'choice_attr' => function($val, $key, $index) {
return ['class' => 'custom-control-input'];
},
'attr'=>['class' =>'custom-checkbox custom-control']
])
->add('email', EmailType::class, [
'label' => "E-Mail"
])
->add('firstName', TextType::class, [
'label' => "First Name"
])
->add('lastName', TextType::class, [
'label' => "Last Name"
])
->add('companyUserPermissionMaps' ,EntityType::class ,[
'required' => true,
'class' => Company::class,
'label' => 'Compañia',
'multiple' => true,
'expanded' => false,
'choice_label' => 'legalName',
'mapped'=>false
])
->add('save', SubmitType::class, [
'label' => "Save"
])
and my controller function looks like this
$user = new User();
$originalRoles = $this->getParameter('security.role_hierarchy.roles');
$options=['roles' => $originalRoles ];
$form = $this->createForm(UserType::class, $user, $options);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$tempPassword = "some pass";
$user->setPassword($encoder->encodePassword(
$user,
$tempPassword
));
$companies=[];
$companiesForm=$form->get('companyUserPermissionMaps')->getData();
foreach ($companiesForm as $value) {
$companies[] = $value->getCompanyId();
}
// Save object to database
$entityManager = $this->getDoctrine()->getManager();
/** #var CompanyRepository $companyRepository */
$companyRepository = $this->getDoctrine()->getRepository(Company::class);
$companiesArr =$companyRepository->findCompanyByArray($companies);
$companyUserPermissionMap = new CompanyUserPermissionMap();
$companyUserPermissionMap->setUser($user);
$companyUserPermissionMap->setCompany($companiesArr);
$entityManager->persist($user);
$entityManager->persist($companyUserPermissionMap);
update
Okay, so I neglected to mention the problem you're actually facing. The form component, smart as it is, will try to call getters and setters when loading/modifying the form data. Since your form contains ->add('companyUserPermissionMaps',..., the form component will call getCompanyUserPermissionMaps on your entity (which will return a currently probably empty collection) and will try to write back to the entity via either setCompanyUserPermissionMaps or add/remove instead of set, if they are present.
Since your field actually behaves as if it holds a collection of Company objects, the setting of those on your User object will obviously fail with the error message you encountered:
Expected value of type "App\Entity\CompanyUserPermissionMap" for association field "App\Entity\User#$companyUserPermissionMaps", got "App\Entity\Company" instead.
which absolutely makes sense. So, this problem can be fixed in different ways. The one way which you apparently already tried was setting mapped to false, but instead of false you used 'false' (notice the quotes), which evaluates to true ... ironically. So to use your approach, you would have to remove the quotes. However, I propose a different approach, which I would much prefer!
end update
My general advice would be to hide stuff you don't want to show. So, in your form builder instead of
->add('companyUserPermissionMaps', EntityType::class, [
'required' => true,
'class' => Company::class,
'label' => 'Compañia',
'multiple' => true,
'expanded' => false,
'choice_label' => 'legalName',
'mapped'=>'false'
])
which obviously already is not a field that handles CompanyUserPermissionMaps but companies instead - so apparently you suspected this is semantically something different, you should go back to the User entity and give it a function getCompanies instead
public function getCompanies() {
return array_map(function ($map) {
return $map->getCompany();
}, $this->getCompanyUserPermissionsMaps());
}
public function addCompany(Company $company) {
foreach($this->companyUserPermissionMaps->toArray() as $map) {
if($map->getCompany() === $company) {
return;
}
}
$new = new CompanyUserPermissionMap();
$new->setCompany($company);
$new->setUser($this);
$this->companyUserPermissionMaps->add($new);
}
public function removeCompany(Company $company) {
foreach($this->companyUserPermissionMaps as $map) {
if($map->getCompany() == $company) {
$this->companyUserPermissionMaps->removeElement($map);
}
}
}
you would then call the field companies (so ->add('companies', ...)) and act on Company entities instead of those pesky maps. (I also don't really like exposing ArrayCollection and other internals to the outside. But hey, that's your decision.)
however, if your Maps are going to hold more values at some point, you actually have to work with the maps in your form, and not just with Company entities.
I got an entity called 'Activity', that defines a relation between 2 more entities, 'Service' and 'Location'.
Both 'Service' and 'Location', use another entity called 'Allocation', to define what services can be used in a concrete location.
When I create a new Activity, after selecting a service I want the location choice field update with the values defined by allocation.
I have followed symfony documentation to create this 'location' dependent choice field in the form.
Dynamic Form Modification
All works great on create/new form, but when i try to edit service field value in an already created Activity, location field does not update and the symfony profiler shows me the following message:
Uncaught PHP Exception Symfony\Component\PropertyAccess\Exception\InvalidArgumentException: "Expected argument of type "AppBundle\Entity\Location", "NULL" given" at F:\xampp\htdocs\gcd\vendor\symfony\symfony\src\Symfony\Component\PropertyAccess\PropertyAccessor.php line 253 Context: { "exception": "Object(Symfony\Component\PropertyAccess\Exception\InvalidArgumentException)" }
This is a section of my Activity Entity
/**
* Activity
*
* #ORM\Table(name="activity")
* #ORM\Entity(repositoryClass="AppBundle\Repository\ActivityRepository")
*/
class Activity
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var Service
*
* #ORM\ManyToOne(targetEntity="Service", fetch="EAGER")
* #ORM\JoinColumn(name="service_id", referencedColumnName="id", nullable=false)
*/
private $service;
/**
* #var Location
*
* #ORM\ManyToOne(targetEntity="Location", fetch="EAGER")
* #ORM\JoinColumn(name="location_id", referencedColumnName="id", nullable=false)
*/
private $location;
My Controller.
/**
* Creates a new Activity entity.
*
* #Route("/new", name="core_admin_activity_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$activity = new Activity();
$form = $this->createForm('AppBundle\Form\ActivityType', $activity);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$locationAvailable = $this->isLocationAvailable($activity);
$activityOverlap = $this->hasOverlap($activity);
if($locationAvailable && !$activityOverlap){
$em = $this->getDoctrine()->getManager();
$em->persist($activity);
$em->flush();
return $this->redirectToRoute('core_admin_activity_show', array('id' => $activity->getId()));
}
}
return $this->render('activity/new.html.twig', array(
'activity' => $activity,
'form' => $form->createView(),
));
}
/**
* Displays a form to edit an existing Activity entity.
*
* #Route("/{id}/edit", name="core_admin_activity_edit")
* #Method({"GET", "POST"})
*/
public function editAction(Request $request, Activity $activity)
{
$deleteForm = $this->createDeleteForm($activity);
$editForm = $this->createForm('AppBundle\Form\ActivityType', $activity);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$locationAvailable = $this->isLocationAvailable($activity);
$activityOverlap = $this->hasOverlap($activity);
if($locationAvailable && !$activityOverlap){
$em = $this->getDoctrine()->getManager();
$em->persist($activity);
$em->flush();
return $this->redirectToRoute('core_admin_activity_show', array('id' => $activity->getId()));
}
}
return $this->render('activity/edit.html.twig', array(
'activity' => $activity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
My FormType
class ActivityType extends AbstractType
{
private $em;
public function __construct(EntityManager $entityManager)
{
$this->em = $entityManager;
}
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('service', EntityType::class, array(
'class' => 'AppBundle:Service',
'placeholder' => 'elige servicio',
))
->add('location', EntityType::class, array(
'class' => 'AppBundle:Location',
'choices' => array(),
))
->add('name')
->add('virtual')
->add('customerSeats')
->add('customerVacants')
->add('employeeSeats')
->add('firstDate', 'date')
->add('lastDate', 'date')
->add('weekday')
->add('beginTime', 'time')
->add('endTime', 'time')
->add('admissionType')
->add('status');
$formModifier = function (FormInterface $form, Service $service = null) {
$locations = null === $service ? array() : $this->em->getRepository('AppBundle:Allocation')->findLocationsByService($service);
$form->add('location', EntityType::class, array(
'class' => 'AppBundle:Location',
'choices' => $locations,
));
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
$data = $event->getData();
$formModifier($event->getForm(), $data->getService());
}
);
$builder->get('service')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
// It's important here to fetch $event->getForm()->getData(), as
// $event->getData() will get you the client data (that is, the ID)
$service = $event->getForm()->getData();
// since we've added the listener to the child, we'll have to pass on
// the parent to the callback functions!
$formModifier($event->getForm()->getParent(), $service);
}
);
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Activity'
));
}
}
javaScript function
<script>
var $service = $('#activity_service');
// When sport gets selected ...
$service.change(function() {
// ... retrieve the corresponding form.
var $form = $(this).closest('form');
// Simulate form data, but only include the selected service value.
var data = {};
data[$service.attr('name')] = $service.val();
// Submit data via AJAX to the form's action path.
$.ajax({
url : $form.attr('action'),
type: $form.attr('method'),
data : data,
success: function(html) {
// Replace current position field ...
$('#activity_location').replaceWith(
// ... with the returned one from the AJAX response.
$(html).find('#activity_location')
);
}
});
});
</script>
Any help will be great, thanks.
I had a similar problem, I found a solution : Symfony - dynamic drop down lists not working only when editing
I had also faced similar issue and on tracing found that it is the EntityType class on other dropdown that is causing the problem while editing the form
The solution is to submit the full form via ajax instead of only one field like in the case of new form.
So change
var data = {};
data[$service.attr('name')] = $service.val();
To
var data = $form.serializeArray()
That should fix the issue.
I am having problem with creating new Collection entity with Form.
I want to create new Collection entity with form and then to be redirected to collections page with 'collection_user_collections' route, and be able to see new collection in user's collections list. But instead when I press submit button on form, I get following error:
No route found for "POST /profile/": Method Not Allowed (Allow: GET, HEAD)
Below is my code:
class Collection{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
private $name;
private $url;
private $type;
const STATUS_PRIVATE = 0;
const STATUS_PUBLIC = 1;
/**
* #ORM\ManyToOne(targetEntity="MyMini\UserBundle\Entity\User", inversedBy="collections")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
private $date_created;
private $date_modified;
/* getters and setters are here*/
}
I am using CollectionType to build form:
class CollectionType extends AbstractType{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name','text')
->add('type', 'choice', array('choices' => array(
Collection::STATUS_PRIVATE => 'Private',
Collection::STATUS_PUBLIC => 'Public',
)))
->add('save', 'submit', array('label' => 'Create Collection'))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'MyMini\CollectionBundle\Entity\Collection'
));
}
public function getName()
{
return 'mymini_collectionbundle_collection';
}
}
This is createAction, here I tried to insert current user's username and date when entity was created. I am using FOSUserBundle to manage app users:
/**
* #Route("/create-collection/", name="collection_create_collection")
* #Template()
*/
public function createAction(Request $request)
{
$collection = new Collection();
$user = $this->get('security.token_storage')->getToken()->getUser();
$username = $user->getUsername();
$form = $this->createForm(new CollectionType(), $collection);
$form->handleRequest($request);
if ($form->isValid() && $form->isSubmitted()) {
$em = $this->getDoctrine()->getManager();
$collection->setUser($user);
$collection->setDateCreated(new \DateTime());
$em->persist($collection);
$em->flush();
return $this->redirectToRoute('collection_user_collections', array('username' => $username));
}
return array('collection'=>$collection, 'form' => $form->createView());
}
Twig for form:
<div class="collection-create">
<h3 id="create-collection">Create a collection</h3>
<a class="close-reveal-modal" aria-label="Close">×</a>
{{ form(form) }}
</div>
The exception you're receiving is expected. You are calling the createForm method without passing all necessary arguments. The right way to create a form is:
$this->createForm(
new CollectionType(),
$collection,
array(
'action' => $this->generateUrl('collection_create_collection') ),
'method' => 'PUT', // or 'POST'
)
);
I have two entities. Container and Schooltype. The entity container have a "oneToMany" relation to entity Schooltype.
Entity Container:
/**
* #ORM\OneToMany(targetEntity="App\MyBundle\Entity\SchoolType", mappedBy="container", cascade={"persist", "remove"})
*/
protected $schooltype;
Entity Schooltype:
/**
* #ORM\ManyToOne(targetEntity="App\MyBundle\Entity\Container", inversedBy="schooltype")
* #ORM\JoinColumn(name="container_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $container;
Now i create a form for container, so i can add one or many schooltypes. In my entity Container i modify the "removeSchooltype" method, it's look like.
Entity Container, remove method for schooltype:
public function removeSchooltype(\App\MyBundle\Entity\SchoolType $schooltype)
{
$this->schooltype->removeElement($schooltype);
$schooltype->setContainer(null);
}
Form ContainerType:
->add('schooltype', 'entity', array(
'class' => 'AppMyBundle:Schooltype',
'choices' => $schoolTypes,
'label' => 'msg.schoolType',
'translation_domain' => 'messages',
'multiple' => true,
'expanded' => false)
)
I try to handle the store process in my controller.
Container controller, edit method:
$object = new Container();
// Exists any object?
if (!$object) {
$this->get('session')->getFlashBag()->add('danger', $this->get('translator')->trans('notfound'));
return $this->redirect($this->generateUrl('app_container_list'));
}
$form = $this->createForm($this->get('form.type.container'), $object)->add('save', 'submit', array('label' => 'save', 'translation_domain' => 'messages', 'attr' => array('class' => 'btn btn-primary')));
$form->handleRequest($request);
// Check if form isValid
if ($form->isValid()) {
// Store object
$em = $this->getDoctrine()->getManager();
$em->persist($object);
// Flush statements
$em->flush();
$em->clear();
$this->get('session')->getFlashBag()->add('info', $this->get('translator')->trans('objectEdited', array()));
return $this->redirect($this->generateUrl('app_container_list'));
}
return $this->render('AppMyBundle:Container:edit.html.twig', array("form" => $form->createView()));
Everything works fine, i can add one or many schooltypes in my container and this was saved successfull. But if i remove a schooltype from selectbox in form and post my form the relation between container and schooltype will not be removed, have someone a hint why this happens?
1 Country to N League. Example below shows you how things are done. Just apply to yours. If you want the full CRUD example for 1 to N relationships, it is here.
Country
class Country
{
protected $id;
/**
* #ORM\OneToMany(
* targetEntity="League",
* mappedBy="country",
* cascade={"persist", "remove"}
* )
*/
protected $league;
public function __construct()
{
$this->league = new ArrayCollection();
}
public function addLeague(League $league)
{
$this->league[] = $league;
return $this;
}
public function removeLeague(League $league)
{
$this->league->removeElement($league);
}
public function getLeague()
{
return $this->league;
}
}
League
class League
{
/**
* #ORM\ManyToOne(
* targetEntity="Country",
* inversedBy="league"
* )
* #ORM\JoinColumn(
* name="country_id",
* referencedColumnName="id",
* onDelete="CASCADE",
* nullable=false
* )
*/
protected $country;
public function setCountry(Country $country)
{
$this->country = $country;
return $this;
}
public function getCountry()
{
return $this->country;
}
}
LeagueType
class LeagueType extends AbstractType
{
private $country;
public function __construct()
{
$this->country = [
'class' => 'FootballFrontendBundle:Country',
'property' => 'name',
'multiple' => false,
'expanded' => false,
'required' => false,
'empty_value' => '',
'query_builder' => function (EntityRepository $repo)
{
return $repo->createQueryBuilder('c')->orderBy('c.name', 'ASC');
}
];
}
public function buildForm(FormBuilderInterface $builder, array $options = [])
{
$builder
->setMethod($options['method'])
->setAction($options['action'])
->add('whatever properties you have in your entitiy')
->add('country', 'entity', $this->country);
}
public function getName()
{
return 'league';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(
['data_class' => 'Football\FrontendBundle\Entity\League']
);
}
}
Controller delete/remove method
/**
* Deletes country.
*
* #param int $id
*
* #Route("/delete/{id}", requirements={"id"="\d+"})
* #Method({"GET"})
*
* #return RedirectResponse|Response
* #throws LeagueException
*/
public function deleteAction($id)
{
try {
$em = $this->getDoctrine()->getEntityManager();
$repo = $em->getRepository('FootballFrontendBundle:League');
$league = $repo->findOneByIdAsObject($id);
if (!$league instanceof League) {
throw new LeagueException(sprintf('League read: league [%s] cannot be found.', $id));
}
$em->remove($league);
$em->flush();
} catch (DBALException $e) {
$message = sprintf('DBALException [%s]: %s', $e->getCode(), $e->getMessage());
} catch (ORMException $e) {
$message = sprintf('ORMException [%s]: %s', $e->getCode(), $e->getMessage());
} catch (Exception $e) {
$message = sprintf('Exception [%s]: %s', $e->getCode(), $e->getMessage());
}
if (isset($message)) {
throw new LeagueException($message);
}
return $this->redirect($this->generateUrl('where ever you want'));
}