I'm currently working on a symfony 5 project and while trying to insert a name in the database, I received this error : An exception occurred while executing a query: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null
The method:
public function add_category(Request $request, EntityManagerInterface $em) : Response
{
$form=$this->createForm(CategoryType::class);
$form->handleRequest($request);
if($form->isSubmitted()){
$category=new Category;
$em->persist($category);
$em->flush();
dump($request);
}
$formView=$form->createView();
return $this->render('admin/category/add_category.html.twig', [
'formView'=>$formView,
]);
}
The formBuilder :
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('name', TextType::class,[
'label'=>'Nom de la catégorie',
'attr'=>[
'class'=>'form-control mb-2',
'placeholder'=>'Nom de la catégorie'
]
]);
}
The twig form:
{{ form_start(formView) }}
{{ form_row(formView.name) }}
<button type="submit" >
<i ></i>Créer la catégorie
</button>
{{ form_end(formView) }}
The property name in the Category Entity:
/**
* @ORM\Column(type="string", length=255)
*/
private $name;
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
CodePudding user response:
It should be like this:
public function add_category(Request $request, EntityManagerInterface $em) : Response
{
// Create new category here
$category=new Category();
// Add $category to createForm method as second argument
$form=$this->createForm(CategoryType::class, $category);
$form->handleRequest($request);
if($form->isSubmitted()){
// After form is submitted
// $category will be filled
// with data from $form
$em->persist($category);
$em->flush();
dump($request);
}
$formView = $form->createView();
return $this->render('admin/category/add_category.html.twig', [
'formView'=>$formView,
]);
}
You can read more about processing forms from the docs.