following a tutorial notfoundhttpexception - exception

i am pretty new to framework and laravel in general, im struggling to learn laravel, and i have found this book.
https://leanpub.com/learninglaravel
I hope is a good start. (usually i coded in php and html)
I have a problem following the basic tutorial (:/ not a good start lol)
Routes.php
Route::post('contact', function()
{
$data = Input::all();
$rules = array(
'subject' => 'required',
'message' => 'required'
);
$validator = Validator::make($data, $rules);
if($validator->fails()) {
return Redirect::to('contact')->withErrors($validator)->withInput();
}
return 'Your message has been sent';
});
Route::get('/', function()
{
return View::make('home');
});
Route::get('about', function()
{
return View::make('about');
});
Contact.blade.php
#extends('layout')
#section('content')
<h1>Contact Us.</h1>
<p>Please contact us by sending a message using the form below:</p>
{{ HTML::ul($errors->all(), array('class'=>'errors'))}}
{{ Form::open(array('url' => 'contact')) }}
{{ Form::label('Subject') }}
{{ Form::text('subject','Enter your subject') }}
<br />
{{ Form::label('Message') }}
{{ Form::textarea('message','Enter your message') }}
<br />
{{ Form::submit() }}
{{ Form::close() }}
#stop
THe other pages works well

You need another route to display the contact form page
Route::get('contact', function() {
return View::make('contact');
});

Related

Looking for a clean way to export data to a CSV that is previously used in a different controller route that renders a Form/DB query

I have a page that has a form that generates a query that renders relevant information from my database:
Render Example
The controller function I use creates the form using Symfony/Doctrine and then calls on a repository function to query the database based on the fields the user has supplied. I then display these results in a table in a twig file for the user to examine.
My issue is I'm fairly new to Symfony and am having an issue then creating an 'export' button where I can somehow grab the form's data that was passed in so I can re-run the repository function in a new route, OR pass the data from the previous query itself to a function in a new route in the controller where I can then turn this data into a CSV file.
I have it working in what feels like a very poor way currently, by adding hidden input fields in the twig file and then grabbing the values from each field and putting together objects in a controller function that I then turn into a CVS.
I'm looking for suggestions on a clean way to get either form data or query data from my exportAction function/route in my ServiceController into a new exportServiceAction function/route (or any other advised methods to accomplish the same goal)
Controller Function
/**
* Creates a form for Exporting Services associated with techs
* #Route("/export", name="service_export", methods={"GET", "POST"})
*/
public function exportActions(Request $request, EntityManagerInterface $em)
{
$staffEntities = $em->getRepository('AppBundle:User')->buildFindByRole('ROLE_STAFF')->getQuery()->getResult();
$staffOptions = [];
foreach ($staffEntities as $staff) {
$staffUsername = $staff->getUsername();
if(!array_key_exists($staffUsername, $staffOptions)) {
$staffOptions[$staffUsername] = $staffUsername;
}
}
$campusEntities = $em->getRepository('AppBundle:Campus')->findBy([], ['name' => 'ASC']);
$campusOptions = [];
foreach ($campusEntities as $campus) {
$campusName = $campus->getName();
if (!array_key_exists($campusName, $campusOptions)) {
$campusOptions[$campusName] = $campusName;
}
}
$buildingEntities = $em->getRepository('AppBundle:Building')->findBy([], ['name' => 'ASc']);
$buildingOptions = [];
foreach ($buildingEntities as $building) {
$buildingName = $building->getName();
if (!array_key_exists($buildingName, $buildingOptions)) {
$buildingOptions[$buildingName] = $buildingName;
}
}
$roomEntities = $em->getRepository('AppBundle:Room')->findBy([], ['name' => 'ASC']);
$roomOptions = [];
foreach ($roomEntities as $room) {
$roomName = $room->getName();
if (!array_key_exists($roomName, $roomOptions)) {
$roomOptions[$roomName] = $roomName;
}
}
$options = [
'techs' => $staffOptions,
'campuses' => $campusOptions,
'buildings' => $buildingOptions,
'rooms' => $roomOptions,
];
$searchForm = $this->createForm('AppBundle\Form\SearchServiceType', [], $options);
$searchForm->handleRequest($request);
if($searchForm->isSubmitted() && $searchForm->isValid()) {
$data = $searchForm->getData();
dump($data);
$queriedAssignments = $em->getRepository('AppBundle:Service')->findForExport($data);
if (empty($queriedAssignments)) {
$queriedAssignments = ["errorMessage" => "No Results Found!"];
}
}
return $this->render('service/export.html.twig', [
'form' => $searchForm->createView(),
'assignments' => $queriedAssignments ?? null,
]);
}
(This is where i'd like to access either the data or queriedAssignments variables to create a CSV)
Repository Function
public function findForExport(array $params = [])
{
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder();
$qb->select('a', 'u', 'bg', 'bsi', 'e', 's')
->from('AppBundle:Assignment', 'a')
->leftJoin('a.staff', 'u')
->leftJoin('a.task', 't')
->leftJoin('a.billingGroup', 'bg')
->leftJoin('bg.billingServiceItems', 'bsi')
->leftJoin('a.eventInstance', 'e')
->leftJoin('e.serviceRequest', 's')
->groupBy('a');
$qb->orderBy('a.date', 'ASC')
->addOrderBy('a.startTime', 'ASC')
->addOrderBy('a.endTime', 'ASC');
if (isset($params['startDate'])) {
$qb->andWhere('a.date >= :startDate')
->setParameter('startDate', $params['startDate']);
}
if (isset($params['endDate'])) {
$qb->andWhere('a.date <= :endDate')
->setParameter('endDate', $params['endDate']);
}
if ($params['promptStaff']) {
if ($this->paramIsNotEmpty($params['techs'])) {
$qb->andWhere('u.username IN (:techs)');
$qb->setParameter('techs', $params['techs']);
$qb->orderBy('u.username', 'ASC')
->addOrderBy('a.date', 'ASC');
}
}
if ([$params['promptLocation']]) {
if ($this->paramIsNotEmpty($params['campusName']) || $this->paramIsNotEmpty($params['buildingName']) || $this->paramIsNotEmpty($params['roomName'])) {
$qb->join('s.location', 'l');
}
}
if ($this->paramIsNotEmpty($params['campusName'])) {
$qb->andWhere('l.campusName IN (:campusName)');
$qb->setParameter('campusName', $params['campusName']);
}
if ($this->paramIsNotEmpty($params['buildingName'])) {
$qb->andWhere('l.buildingName IN (:buildingName)');
$qb->setParameter('buildingName', $params['buildingName']);
}
if($this->paramIsNotEmpty($params['roomName'])) {
$qb->andWhere('l.roomName IN (:roomName)');
$qb->setParameter('roomName', $params['roomName']);
}
if ($this->paramIsNotEmpty($params['campusName']) || $this->paramIsNotEmpty($params['buildingName']) || $this->paramIsNotEmpty($params['roomName'])) {
$qb->orderBy('l.campusName', 'ASC')
->addOrderBy('l.buildingName', 'ASC')
->addOrderBy('l.roomName', 'ASC')
->addOrderBy('a.date', 'ASC')
->addOrderBy('a.startTime', 'ASC')
->addOrderBy('a.endTime', 'ASC');
}
if ($this->paramIsNotEmpty($params['searchVenue'])) {
$qb->leftJoin('s.location', 'l');
$qb->andWhere(
$qb->expr()->orX(
$qb->expr()->like('l.venueName', ':searchVenue'),
$qb->expr()->like('l.venueAddress', ':searchVenue'),
$qb->expr()->like('l.venueCity', ':searchVenue'),
$qb->expr()->like('l.venueState', ':searchVenue'),
$qb->expr()->like('l.venueZipCode', ':searchVenue')
)
);
$qb->setParameter('searchVenue', '%'.$params['searchVenue'].'%');
$qb->orderBy('l.venueState', 'ASC')
->addOrderBy('l.venueCity', 'ASC')
->addOrderBy('l.venueName', 'ASC')
->addOrderBy('a.date', 'ASC')
->addOrderBy('a.startTime', 'ASC')
->addOrderBy('a.endTime', 'ASC');
}
if ($this->paramIsNotEmpty($params['startTime'])) {
$qb->andWhere('a.startTime >= :startTime');
$qb->setParameter('startTime', $params['startTime']);
}
if ($this->paramIsNotEmpty($params['endTime'])) {
$qb->andWhere('a.endTime <= :endTime');
$qb->setParameter('endTime', $params['endTime']);
}
return $qb->getQuery()->getResult();
}
protected function paramIsNotEmpty($param)
{
return $param instanceof ArrayCollection ? !$param->isEmpty() : !empty($param);
}
Form
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('startDate', DateTimeType::class, [
'widget' => 'single_text',
'required' => false,
'html5' => false,
'attr' => ['class' => 'date', 'placeholder' => 'e.g. mm/dd/yyyy', 'autocomplete' => 'off'],
'format' => 'MM/dd/yyyy',
])
->add('endDate', DateTimeType::class, [
'widget' => 'single_text',
'required' => false,
'html5' => false,
'attr' => ['class' => 'date', 'placeholder' => 'e.g. mm/dd/yyyy', 'autocomplete' => 'off'],
'format' => 'MM/dd/yyyy',
])
->add('searchVenue', SearchType::class, [
'required' => false,
'label' => 'Venue Search (Name, Address, City, State, Zip)',
'attr' => ['placeholder' => 'Press Enter to Search']
])
->add('promptStaff', CheckboxType::class, [
'required' => false,
'label' => 'Filter by Staff'
])
->add('promptLocation', CheckboxType::class, [
'required' => false,
'label' => 'Filter by Location'
])
->add('promptTime', CheckboxType::class, [
'required' => false,
'label' => 'Filter by Time'
])
->add('promptVenue', CheckboxType::class, [
'required' => false,
'label' => 'Search Venues'
])
->add('techs', ChoiceType::class, array(
'required' => false,
'expanded' => true,
'multiple' => true,
'label' => 'Staff Username',
'choices' => $options['techs']
))
->add('campusName', ChoiceType::class, array(
'required' => false,
'expanded' => true,
'multiple' => true,
'choices' => $options['campuses']
))
->add('buildingName', ChoiceType::class, array(
'required' => false,
'expanded' => true,
'multiple' => true,
'choices' => $options['buildings']
))
->add('roomName', ChoiceType::class, array(
'required' => false,
'expanded' => true,
'multiple' => true,
'choices' => $options['rooms']
))
->add('startTime', ChoiceType::class, array(
'choices' => $times,
'required' => false,
'placeholder' => 'Please Select'
))
->add('endTime', ChoiceType::class, array(
'choices' => $times,
'required' => false,
'placeholder' => 'Please Select'
));
}
Twig
{% block body %}
<h1>Staff Time Export</h1>
{{ form_start(form) }}
{{ form_row(form.startDate) }}
{{ form_row(form.endDate) }}
<div class="filter-prompts">
{{ form_row(form.promptStaff) }}
{{ form_row(form.promptLocation) }}
{{ form_row(form.promptTime) }}
</div>
<div class="staff-select">
{{ form_row(form.techs) }}
</div>
<div class="location-select">
{{ form_row(form.promptVenue)}}
<div class="location-on-campus">
{# dropdowns #}
{{ form_row(form.campusName) }}
{{ form_row(form.buildingName) }}
{{ form_row(form.roomName) }}
</div>
<div class="location-off-campus">
{{ form_row(form.searchVenue) }}
</div>
</div>
<div class="time-select">
{{ form_row(form.startTime)}}
{{ form_row(form.endTime)}}
</div>
<div class="button-container">
<button class="button button--grey" type="submit">Search</button>
</div>
{{ form_end(form) }}
{% if assignments is not null and assignments is not empty and assignments.errorMessage is not defined %}
<form action="{{ path('service_export_do')}}" method="post">
<table class="table--dashboard">
<thead>
<tr>
<th>Task Description</th>
<th>Staff Name</th>
<th>Username</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
<th>Hours</th>
<th>Unit Cost</th>
</tr>
</thead>
<tbody>
{% for assignment in assignments %}
<tr>
<td><input type="hidden" name="serviceIDs[]" value="{{ assignment.id }}"></input>{{ assignment.task.description ?? 'n/a'}}</td>
<td>{{ assignment.staff.lastname }}, {{ assignment.staff.firstname }}</td>
<td> {{ assignment.staff.username }}</td>
<td> {{ assignment.date|date("m/d/Y") }}</td>
<td> {{ assignment.startTime|date("H:i:s") }}</td>
<td> {{ assignment.endTime|date("H:i:s") }}</td>
<td> {% for billingServiceItem in assignment.billingServiceItems %}
{% if billingServiceItem.hours %}{% endif %}
{{ billingServiceItem.hours }}
{% else %}
0
{% endfor %}</td>
<td> {% for billingServiceItem in assignment.billingServiceItems %}
${{ billingServiceItem.unitCost }}
{% endfor %}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="button-container">
<button class="button button--grey" name="export_all" type="submit">Export</button>
</div>
</form>
{% elseif (assignments.errorMessage is defined)%}
<h1>
{{ assignments['errorMessage'] }}
</h1>
{% endif %}{% endblock %}
(Here I left out all but one of the hidden input types i was using previously for legibility)
Some things I've tried based off google searches (maybe not very well):
Passing the data to the route via a route parameter:Symfony Docs on Route Parameters
Creating a private variable in the controller for the data , then accessing it via getter/setters (Yes dumb, I was desperate)
Trying to move the export button into the same form as the query and rendering it conditionally, then adding a href path to a new controller route
Somehow trying to re-render the form again and re-querying it using the same information and then turning that data into the CSV
I feel like I'm missing a very simple way to add a function and/or route here that uses the same data that the user used to query and display the table, to create a csv. Thank you in advance for any suggestions and sorry if this is is hard to understand.
EDIT: What I ended up doing
So after trying some of these helpful suggestions, what I found to be the easiest solution for me at my experience level was to simply grab the ID from each entry from my query via a hidden input tag. In my controller I created a new route for creating a cvs and grabbed the IDs using $request->request->get('IdsFromEntries'); I then created a new function in my repository that joined related tables I needed for the fields I wanted that were related to these entries. I was then able to loop through this query data and assign each field to a column for my cvs. Doing this I was able to keep my front end the same and have the user simply click the export button at the button of my search results table to download the cvs containing the table's data.
The simplest way would be to add some optional suffix in your current route like .csv. If it is set then get all data that you need and create CSV with it.
This way you don't need to create new controller and extract your duplicating code... Just add one condition and return rendered page in one case and CSV file in another.
I had a similiar issue to be resolved. I created two routes.
One route showed the user interface including the form, a table of data and an export button. The second route was justed used to export the data. Both routes were connected to the same form. Because the selection of the user could be shared publicly without leaking any secrets, the attached form used the http verb "GET" effectivly attaching the users selection as a query string parameter to the view route. When rendering the export button, I concatenated the export routes path with the query string.
This way I was able to separate both actions into two routes and share content between them, no cookies or js needed.

HTML tag displaining plainly instead of being processed [duplicate]

This question already has answers here:
HTML in Symfony2 form labels instead of plain text
(9 answers)
Closed 1 year ago.
I'm using the following simple controller function to create a form:
$json = json_decode(file_get_contents('../data/sample.json'));
public function index(Request $request): Response
{
$form = $this->createFormBuilder();
$form->add('city', ChoiceType::class, [
'choices' => $json[0]->options,
'label' => $json[0]->label,
]);
$form->add('submit', SubmitType::class, [
'attr' => [
'class' => 'btn btn-primary'
],
]);
$form->add('next', SubmitType::class, [
'attr' => [
'class' => 'btn btn-warning',
'disabled' => true
]
]);
$form = $form->getForm();
.
.
.
return $this->render('quiz/index.html.twig', [
'form' => $form->createView(),
]);
}
The data is read from the following same json file :
[
{
"options" : ["Lisbon", "London", "Los Angels"],
"label" : "Please select your <u>city</u> of residence"
}
]
Each of the labels has some HTML tag(s) in them but all of those tags are not being processed. So the example above displays in my browser exactly as seen in the code.
In my twig template, I have tried each one of the following but individually:
{{ form(form) }}
{{ form(form) | raw }}
{{ form(form) | convert_encoding('UTF-8', 'iso-2022-jp') }}
{{ form(form) | convert_encoding('UTF-8', 'HTML-ENTITIES') }}
{% autoescape false %}
{{ form(form) | convert_encoding('UTF-8', 'HTML-ENTITIES') }}
{% endautoescape %}
{{ form(form) | striptags('<u><input><p><select><option><br><b><button>') }}
{{ form(form) | striptags('<u><input><p><select><option><br><b><button>') | raw }}
Despite all those suggestions I found online, my form labels still display unprocessed HTML tags.
An potential added complication is that I print the entire form as one whole using {{ form(form) }}. However because the form is dynamically assemble from JSON data, it's not really possible to print the form in segments because the JSON data can be added to or removed from at any time.
Well the answer turned out to be rather simple.
In order to include HTML tags in the label, label_html => true needs to be set on the formgroup, according to this post.

Can't get input value with Twig

Hello I was trying to pass some arguments but I don't know how to get value of input using twig here is my code :
okey first of all im displaying the blog details using this detailsaction which also rendering a form to add comments to the blog ;
public function detailsAction(Request $request,Blog $blog){
$user=$this->getUser();
if($user==null)
return $this->redirectToRoute('fos_user_security_login');
$add_comment = new CommentaireBlog();
$em = $this->getDoctrine()->getManager();
$comments = $em->getRepository(CommentaireBlog::class)->findByBlog($blog);
$add_comment->setBlog($blog);
$add_comment->setUser($user);
$add_comment->setDate( new \DateTime());
$form = $this->createFormBuilder($add_comment)
->add('contenu', TextareaType::class)
->getForm();
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$add_comment = $form->getData();
$em = $this->getDoctrine()->getEntityManager();
$em->persist($add_comment);
$em->flush();
return $this->redirectToRoute('blog_details', array('id' => $blog->getId()));
}
}
return $this->render('blog/details.html.twig', array(
'form' => $form->createView(),
'comment' => $add_comment,
'blog' => $blog,
'comments'=>$comments,
));
}
twig page:
{{ form_start(form) }}
<div class="row form-group">
<div class="col col-md-3"><label class=" form-control-label">Votre Commentaire </label></div>
<div class="col-12 col-md-9"> {{ form_widget(form.contenu, { 'attr': {'class': 'form-control'} }) }}<small class="form-text text-muted"></small></div>
<button type="submit" class="btn btn-default">Envoyer</button>
<div class="col-12 col-md-9">
</div>
</div>
{{ form_end(form) }}
now what i want to do is that after someone add a comment and its(racist/verbual abuse..) an other user can report the comment and a mail will be sent so i used reportAction which take three arguments the reason the message and comment id
public function reportAction($msg,$type,$id)
{
}
i still didnt write inside it cause first of all i need to the value of inputs so i went to the twig page and i made this little form to get inputs but idk how to get the value
here is the form :
<div class="modal-body">
<form id="lala" method="GET">
<label for="cars">Reason:</label>
<select id="reportreason">
<option value="Inappropriate Content">Inappropriate Content</option>
<option value="Spam">Spam</option>
<option value="Racism">Racism</option>
<option value="Nudity">Nudity</option>
<option value="Other">Other</option>
</select>
<div class="form-group">
<label for="message-text" class="col-form-label">Message:</label>
<textarea id="reportmessage" class="form-control" id="message-text"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<a id="reportlink" href="{{ path('comment_report', { 'msg': form.vars.data.reportmessage ,'type': form.vars.data.reportreason, 'id': comment.id }) }}" type="button" class="btn btn-primary">Send message</a>
</div>
this is yml file :
blog_details:
path: /{id}/details
defaults: { _controller: "BlogBundle:Blog:details" }
methods: [GET, POST]
comment_report:
path: /{msg}/{type}/{id}/report
defaults: { _controller: "BlogBundle:Blog:report" }
methods: [GET, POST]
but im getting this error now :
Neither the property "reportmessage" nor one of the methods "reportmessage()", "getreportmessage()"/"isreportmessage()" or "__call()" exist and have public access in class "BlogBundle\Entity\CommentaireBlog".
so how can i get get the value of the inputs using twig ?
Twig Object Syntax https://twigfiddle.com/01iobj
Effectively the twig error message is saying that in your path() arguments, you are passing an object without an associated key as {value} The correct syntax would be {key: value} or [value], resembling a JSON syntax.
{
"key1": { "key1a": "value1a" },
"key2": ["value2"],
"key3": "value3"
}
Result
$_GET = array(
'key1' => array('key1a' => 'value1a'),
'key2' => array('value2'),
'key3' => 'value3'
);
A different approach
Looking at what you want to do, you need to refactor your approach.
First change your controller pathing for ONLY the comment.
blog_details:
path: /{id}/details
defaults: { _controller: "BlogBundle:Blog:details" }
methods: [GET, POST]
comment_report:
path: /{comment}/report
defaults: { _controller: "BlogBundle:Blog:report" }
methods: [POST]
Next create a form instance for your modal, this will allow you use the FormInstance for rendering and validating the submitted form elsewhere. Ensuring that all of the validation occurs and you're not having to update different scripts for the same form.
/* /src/Form/CommentReportForm.php */
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type as Form;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints as Assert;
class CommentReportForm extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('reason', Form\ChoiceType::class [
'choices' => [
'Inappropriate Content' => 'Inappropriate Content',
'Spam' => 'Spam',
'Racism' => 'Racism',
'Nudity' => 'Nudity',
'Other' => 'Other'
]
])
->add('message', Form\TextType::class, [
'constraints' => [
new Assert\Length(['min' => 10]),
new Assert\NotBlank(),
],
]);
}
public function getBlockPrefix()
{
return 'report_comment_form';
}
}
Next, update your Controller actions accordingly.
public function detailsAction(Request $request, Blog $blog)
{
if (!$user = $this->getUser()) {
//this should be handled in your firewall configuration!!!!
return $this->redirectToRoute('fos_user_security_login');
}
$em = $this->getDoctrine()->getManager();
$add_comment = new CommentaireBlog();
$add_comment->setBlog($blog);
$add_comment->setUser($user);
$add_comment->setDate(new \DateTime());
$form = $this->createFormBuilder($add_comment)
->add('contenu', TextareaType::class)
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
//Symfony form sets values for the model by_reference
$em->persist($add_comment);
$em->flush();
return $this->redirectToRoute('blog_details', array('id' => $blog->getId()));
}
/*
* create the report form
*/
$reportForm = $this->createForm(\App\Form\CommentReportForm::class);
$reportForm->handleRequest($request);
return $this->render('blog/details.html.twig', array(
'form' => $form->createView(),
'comment' => $add_comment,
'blog' => $blog,
'comments'=> $em->getRepository(CommentaireBlog::class)->findByBlog($blog),
/*
* give the report form a different name in twig
*/
'report_form' => $reportForm->createView(),
));
}
public function reportAction(Request $request, CommentaireBlog $comment)
{
$reportForm = $this->createForm(\App\Form\CommentReportForm::class);
$reportForm->handleRequest($request);
/** #var array|string[message, reason] */
$reportData = $reportForm->getData();
/*
array( 'reason' => 'value', 'message' => 'value' )
*/
dump($reportData);
if ($reportForm->isSubmitted() && $reportForm->isValid()) {
//send email
//redirect to success message
}
//display an error message
}
Lastly update your view to support the new form in your modal.
<div class="modal-body">
{{ form_start(report_form, { action: path('comment_report', { comment: comment.id }) })
{{ form_label(report_form.reason) }}
{{ form_widget(report_form.reason) }}
<div class="form-group">
{{ form_label(report_form.message) }}
{{ form_widget(report_form.message) }}
</div>
{{ form_end(report_form) }}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Send message</button>
</div>
As a recommendation, I strongly urge you to record the report submissions in the database, to function as a case log and status of the reports. My approach will get you most of the way there, you would just need to create your App\Entity\CommentReport entity, with an optional association to the CommentaireBlog entity. Which would be passed to the form and adding the data_class to the form options resolver, mimicking what you have done in your other database forms.
I don't know why you wrote your path call like that, but there should not be any round brackets about the variables you want to use in your route. The following code should work:
<a
href="{{ path('comment_report', { 'msg': form.reportmessage.value ,'type': form.reportreason.value, 'id': comment.id }) }}"
type="button"
class="btn btn-primary">
Send message
</a>

How can I display required fields error (validation) message with symfony formbuilder?

PagesController.php
$id = $request->request->get('id');
$target = $request->request->get('target');
$EntityName = 'App\\Entity\\' . ucwords($slug);
$em = $this->getDoctrine()->getManager();
$cmf = $em->getMetadataFactory();
$classes = $cmf->getMetadataFor($EntityName);
if($request->request->get('target')){
$item = new $EntityName();
$item= $this->getDoctrine()->getRepository($EntityName)->find($id);
$formBuilder = $this->createFormBuilder($item);
foreach ($classes->fieldMappings as $fieldMapping) {
$formBuilder->add($fieldMapping['fieldName'], TextType::class, array('attr' => array('class' => 'form-control'), 'required' => true,));
}
$formBuilder->add('cancel', ButtonType::class, array('label' => 'Cancel','attr' => array('class' => 'cancel form-btn btn btn-default pull-right close_sidebar close_h')))
->add('save', SubmitType::class, array('label' => 'Save','attr' => array('id' => 'submit-my-beautiful-form','class' => 'form-btn btn btn-info pull-right','style' => 'margin-right:5px')));
$form = $formBuilder->getForm();
$form->handleRequest($request);
$response = new JsonResponse(
array(
'message' => 'Success',
'output' => $this->renderView('form.html.twig',
array(
'target' => $target,
'entity' => $item,
'form' => $form->createView(),
))), 200);
return $response;
} else {
$em = $this->getDoctrine()->getManager();
foreach ($classes->fieldMappings as $fieldMapping) {
$func = 'set'.$fieldMapping['fieldName'];
$args = $data['form['.$fieldMapping['fieldName'].']'];
$entity->$func($args);
}
$em->persist($entity);
$em->flush();
$response = new JsonResponse(array('id' => $data['form[id]']), 200);
return $response;
}
form.html.twig
<section class="content-header" style="margin-bottom:20px">
<h1 style="float:left;margin-bottom:30px">Create Entry </h1>
</section>
<section class="content" style="clear:left">
<div class="form-group">
{{ form_start(form) }}
{{ form_end(form) }}
</section>
My form is working well, when I fill it out and press the "Save" Button it is stored in the database.
When I leave all fields empty and press "Save" nothing is happening and I get a 500 Error
An exception occurred while executing 'INSERT INTO members (username,
password, email, is_active) VALUES (?, ?, ?, ?)' with params ["",
null, "", "1"]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column
'password' cannot be null
This is actually fine, because the fields are required, but the errors are not displayed in my form, even if I added "required" = "true".
So when using the form builder, you have access to:
$form->isSubmitted()
and
$form->isValid()
As a result you can do something like:
if ($form->isSubmitted() && $form->isValid()) {
// save to database
}
We want to check the form is submitted before we check it's valid as if the form isn't submitted, it's unnecessary to check it's valid as it will be false.
This is going to prevent your MySQL error because your form technically isn't valid and you're trying to flush invalid data. We obviously only want to save our data when it's valid.
Of course, if the form fails you can return the view and in the template, you have access to
{{ form_errors() }}
This will probably cover what you need but you could also pass to your template something like
'formHasErrors' => $form->isSubmitted() && !$form->isValid(),
and then in your template
{% if formHasErrors %}
Something else you may want to do, this allows you to have more control over your fields, is separate out the field out like below:
{{ form_start(form) }}
{{ form_label(form.name) }}
{{ form_errors(form.name, {'attr': {'class': 'form-input'}}) }}
{{ form_widget(form.name) }}
{{ form_end(form) }}
It is very important you catch errors and handle them correctly. Your implementation didn't verify the form is valid which is why you were getting 500 errors.

How to display JSON Array in Blade view?

My db table structure
I'm using a view composer to get data from this table and send it back to my view
class NavComposer
{
public function compose(View $view)
{
if (Auth::check()) {
$view->with('unread_notifications', DB::table('notifications')->where([
['read_at', '=', NULL],
['notifiable_id', '=', Auth::user()->id],
])->get());
}
}
}
My view:
#foreach($unread_notifications as $notification)
{{ $notification->data }}
#endforeach
What I am getting:
{"id":79,"sender":"Diana","receiver":"Alex","subject":"Subject","body":"Lorem ipsum"}
What I want to display:
ID: 79
Subject: Subject
Body: Lorem Ipsum
I apologize in advance if this is very simple stuff I dont know much about JSON
You need to decode JSON. You can do this manually:
#foreach($unread_notifications as $notification)
<?php $notificationData = json_decode($notification->data, true); ?>
{{ $notificationData['sender'] }}
#endforeach
Or you can create accessor so Laravel could automatically convert JSON to an array:
public function getDataAttribute($value)
{
return json_decode($value, true);
}
#foreach($unread_notifications as $notification)
#foreach(json_decode($notification->data, true) as $d)
<div>ID: {{ $d['id'] }}</div>
<div>Subject: {{ $d['subject'] }}</div>
<div>Body: {{ $d['body'] }}</div>
#endforeach
#endforeach