Symfony form not shown in template - symfony

In a Symfony 3.4 project, I just created a new form type ProductSearchType. The form fields are not shown in twig template. There are only the <form> tags, but nothing between them.
FormType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class, [
'required' => false,
'label' => 'Name',
])
->add('sizes', EntityType::class, [
'required' => false,
'label' => 'Bauform',
'class' => ProductSize::class,
])
->add('description', TextType::class, [
'required' => false,
'label' => 'Beschreibung',
])
->add('price', EntityType::class, [
'required' => false,
'label' => 'Preiskategorie',
'class' => ProductPrice::class,
])
->add('booster', EntityType::class, [
'required' => false,
'label' => 'Hörverlust',
'class' => ProductBooster::class,
])
->add('brand', EntityType::class, [
'required' => false,
'label' => 'Marke',
'class' => ProductBrand::class,
]);
}
Action:
public function index(Request $request): Response
{
$products = $this->getDoctrine()->getRepository(Produkt::class)
->findBy([
'showOnEmptySearch' => true,
], [
'sortOnEmptySearch' => 'asc',
]);
$searchForm = $this->createForm(ProductSearchType::class);
$searchForm->handleRequest($request);
$params = [
'products' => $products,
'search_form' => $searchForm->createView(),
];
return $this->render('Products/index.html.twig', $params);
}
Twig part:
{% block template_filter %}
<h1>
Suche
</h1>
<div class="filter_box">
{{ form(search_form) }}
</div>
{% endblock %}

I recommend to follow the documentation. On your example:
$searchForm = $this->createForm(ProductSearchType::class); should be:
$searchForm = $this->createForm(ProductSearchType::class)->getForm();.
Also on twig;
{{ form_start(search_form) }}
{{ form_widget(search_form) }}
{{ form_end(search_form) }}
Here is the documentation link. Welcome to Stackoverflow.
If you get answer to your question, don't forget to mark this answer as Accepted Answer.

Related

Symfony 5 - display an required input field after a specify dropdown select

I would like to build a form with Symfony 5 that should display a required input field for a certain dropdown selection.
After selecting "sonstiges" I need a required input field.
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('salutation', ChoiceType::class, [
'label' => 'salutation',
'required' => true,
'constraints' => [
new NotBlank()
],
'placeholder' => 'Bitte wählen',
'label_attr' => [
'class' => 'visually-hidden'
],
'choices' => [
'Herr' => 'herr',
'Frau' => 'frau',
'Diverse' => 'diverse',
],
])
->add('firstname', TextType::class, [
'label' => false,
'required' => true,
'constraints' => [
new NotBlank()
],
'attr' => [
'placeholder' => "firstname",
],
])
->add('afterWork', ChoiceType::class, [
'label' => 'afterWork',
'required' => true,
'constraints' => [
new NotBlank()
],
'placeholder' => 'Bitte wählen',
'label_attr' => [
'class' => 'visually-hidden'
],
'choices' => [
'Studium' => 'studium',
'weitere Schule' => 'weiterSchule',
'Ausbildung' => 'ausbildung',
'Sonstiges' => 'sonstiges',
],
])
}
I added a $builder->addEventListener, unfortunately it didn't give me the result I need, I also added the input field as not required, hidden it and displayed it with a javascript. Unfortunately, it will not be validated because it is not required in the $builder.
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) {
$form = $event->getForm();
// this would be your entity, i.e. SportMeetup
$data = $event->getData();
if (!is_null($data) && $data['afterWork'] == "sonstiges") {
$form->add('afterWorkText', TextType::class, [
'label' => "afterWorkText",
'required' => false,
'constraints' => array(
new NotBlank(),
),
'attr' => [
'placeholder' => "afterWorkText"
],
'label_attr' => [
'class' => 'visually-hidden'
],
]);
}
}
Is there a way to insert this field with "display:none" attribute and activate it with a javascript? In addition, the field should then be set to required.
Or can someone help me to find the right solution here?

Symfony - How i can get all selected files from request with bellow the name

enter image description here
<input type="file" id="admin_novelty_NoveltyGrants_0_file" name="admin_novelty[NoveltyGrants][0][file]" required="required" multiple="multiple" class="form-control-file">
I have a table grantProduct with 2 mainly properties are title and URL
this is my formType.php. but this is just sub-form. it is included in another form.
$builder
->add('title', InputType\TextType::class, [
'label' => 'novelty.common.title',
'required' => true,
'trim' => true,
'attr' => array(
'placeholder' => 'タイトルを入力ください'
),
'constraints' => [
new Assert\NotBlank(),
]
])
->add('url', InputType\TextType::class, [
'label' => 'novelty.common.url',
'required' => true,
'trim' => true,
'constraints' => [
new Assert\NotBlank(),
]
])
->add('file', FileType::class, [
'multiple' => false,
'mapped' => false,
'attr' => [
'multiple' => 'multiple'
],
])
;
How i can get file input value after selecting some local files?
You can get your file(s) as such $files = $form['file']->getData();
You can loop over each and do what you want
$files = $form['file']->getData();
foreach($files as $file) {
//do what you want with file
}

Use an integer field to store the selectged days with bitwise op

I'm writing a form which contains all days of the week, but theses days are save in an int field $days. I'm using bitwise-op to display the selected days.
{% if (day.days b-and 1) == 1 %}
{{ "sunday" |trans }}
{% endif %}
{% if (day.days b-and 2) == 2 %}
{{ "monday" |trans }}
{% endif %}
....
I don't know how to do to display the checkbox array and convert it into an int and the opposite.
Here is a part of the formtype
$informations = $builder->create('information', FormType::class, [
'label'=>'Information',
'inherit_data' => true,
'label_attr' => ['class'=>'catlabel']])
->add('categoryQualityView', ChoiceType::class, [
'required' => true,
'label' => 'viewQuality',
'choices' => PlaceRepository::$categoriesRates,
'attr' => [
'class' => 'selectpicker',
],
])
->add('categoryGastronomy', ChoiceType::class, [
'label' => 'Gastronomy',
'required' => true,
'choices' => PlaceRepository::$categoriesGastronomy,
'attr' => [
'class' => 'selectpicker',
],
])
->add('price', MoneyType::class, [
'required' => false,
'label' => 'Price',
])
->add('days', IntegerType::class, [
'required' => false,
'label' => 'Days',
])
->add('description', TextType::class, [
'required' => false,
'label' => 'Description',
])
;
For your case you can create a custom "Form Field Type" (and maybe if needed a custom Data Transformer) and customize also the form template as described in the docs.
For example:
class DaysOfWeekType extends AbstractType
{
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'choices' => [
'Monday' => 1,
'Tuesday' => 2,
...
],
]);
}
public function getParent(): string
{
return ChoiceType::class;
}
}

How can I change error message in Symfony

I create a form and then when I click on submit button, show this error message:
Please select an item in the list.
How can I change this message and style it ( with CSS )?
Entity:
...
/**
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank(message="Hi user, Please select an item")
*/
private $name;
...
Controller:
...
public function index(Request $request)
{
$form = $this->createForm(MagListType::class);
$form->handleRequest($request);
return $this->render('index.html.twig', [
'form' => $form->createView()
]);
}
...
Form:
...
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', EntityType::class,[
'class' => InsCompareList::class,
'label' => false,
'query_builder' => function(EntityRepository $rp){
return $rp->createQueryBuilder('u')
->orderBy('u.id', 'ASC');
},
'choice_label' => 'name',
'choice_value' => 'id',
'required' => true,
])
->add('submit', SubmitType::class, [
'label' => 'OK'
])
;
...
}
In order to use custom messages, you have to put 'novalidate' on your HTML form. For example:
With Twig:
{{ form_start(form, {attr: {novalidate: 'novalidate'}}) }}
{{ form_widget(form) }}
{{ form_end(form) }}
Or in your controller:
$form = $this->createForm(MagListType::class, $task, array( //where task is your entity instance
'attr' => array(
'novalidate' => 'novalidate'
)
));
This Stackoverflow answer has more info on how to use novalidate with Symfony. You can also check the docs for more info.
As for the styling, you can use JavaScript to trigger classes, which you can then style in your CSS, like in this example taken from Happier HTML5 Form Validation . You can also take a look at the documentation on MDN and play with the :valid and :invalid selectors.
const inputs = document.querySelectorAll("input, select, textarea");
inputs.forEach(input => {
input.addEventListener(
"invalid",
event => {
input.classList.add("error");
},
false
);
});
EDIT:
You are probably not seeing your custom message because it comes from server side, the message that you're currently seeing when submitting your form is client-side validation. So you can either place novalidate on your field, or you can override the validation messages on the client side by using setCustomValidity(), as described in this SO post which also contains many useful links. An example using your Form Builder:
$builder
->add('name', EntityType::class,[
'class' => InsCompareList::class,
'label' => false,
[
'attr' => [
'oninvalid' => "setCustomValidity('Hi user, Please select an item')"
]
],
'query_builder' => function(EntityRepository $rp){
return $rp->createQueryBuilder('u')
->orderBy('u.id', 'ASC');
},
'choice_label' => 'name',
'choice_value' => 'id',
'required' => true,
])
->add('submit', SubmitType::class, [
'label' => 'OK'
]);

Uploading Image to symfony 3 from form

I am trying to make a sell item page. The form and page render
I'm not entirely sure what I am doing wrong, but when I hit the submit I get an error 500. There might be a syntax error that I am not catching
I have the parameter set as image_directory: '%kernel.root_dir%/../web/images'
class SellPage extends Controller
{
/**
* #Route("/SellItem", name="Sell_Item")
*/
public function goToSellPage(Request $request)
{
$item = new Item();
$sellForm = $this->createFormBuilder($item)
->setMethod("POST")
->add('name', TextType::class, array('label' => 'Item Name: ', 'attr' => array('class' => 'form-control form-group')))
->add('price', TextType::class, array('label' => 'Price: ', 'attr' => array('class' => 'form-control form-group')))
->add('image', FileType::class, array('label' => 'Image Upload Click Here', 'attr' => array('class' => 'btn btn-lg form-group')))
->add('description', TextareaType::class, array('label' => 'Description', 'attr' => array('class' => 'form-control form-group')))
->add('category', EntityType::class, array('class' => 'AppBundle\Entity\Category', 'choice_label' => 'name', 'label' => 'Category', 'attr' => array('class' => 'form-control form-group')))
->add('seller', EntityType::class, array('class' => 'AppBundle\Entity\User', 'choice_label' => 'userName', 'label' => 'Seller', 'attr' => array('class' => 'form-control form-group')))
->add('save', SubmitType::class, array('label' => 'Submit', 'attr' => array( 'class' => 'btn btn-lg btn-success form-group')))
->getForm();
$sellForm->handleRequest($request);
if ($sellForm->isValid())
{
$formData = $request->request->get('sellForm');
$item->setName($formData['name']);
$item->setPrice($formData['price']);
$item->setDescription($formData['description']);
$repository = $this->getDoctrine()->getManager()->getRepository('AppBundle:User');
$item->setSeller($repository->getUserByName($item->getSeller()));
$item->setBuyer($repository->find(2));
$fileName = 'http://sfsuse.com/~sp17g01/sp17g01/web/images/'.md5(uniqid()).$sellForm['image']->getData()->guessExtension();
$sellForm['image']->getData()->move(
$this->getParameter('image_directory'),
$fileName);
$item->setImage($fileName);
$catRepository = $this->getDoctrine()->getManager()->getRepository('AppBundle:Category');
$item->setCategory($catRepository->find(1));
$em = $this->getDoctrine()->getManager();
$em->persist($item);
$em->flush();
}
return $this->render('default/SellItem.html.twig',['sellForm' => $sellForm->createView(),]);
}
}
In you parameters.yml file use:
image_directory: images
And I also think you need to change $filename like so:
$fileName = 'images/'.md5(uniqid()).$sellForm['image']->getData()->guessExtension();
If you are getting errors, it's best to append app_dev.php to your symfony app URL (debug URL). So for example on localhost use:
http://localhost/app_dev.php
And then point to route by appending the route, example:
http://localhost/app_dev.php/myRoute
Then you will get more debug info. I suggestion using the deubg URL for development use.
Try to use this construction:
if ($form->isSubmitted()) {
if ($form->isValid()) {
$img = $user->getImg();
if ($img !== null) {
$img = $user->getImg();
$fileName = md5(uniqid()).'.'.$img->getExtension();
$img->move(
$this->getParameter('user_images'),
$fileName
);
$user->setImg($fileName);
}
}
}

Resources