I am new to Symfony. I have seen a lot of threads regarding this topic, but none have been able to answer the question that I have.
I have a "Contact" form on my site. This contact form submits to path('submit_query'), which calls the submitQueryController. I am not building the form through Symfony and I am not using an object or entity. My problem is that no matter what I do, I am unable to access the form data within the controller. I have tried every thread suggestion that I have seen, and I either get the REQUEST object with a whole bunch of data (none of which is my form data) or I get nothing.
Is there no easy way of accessing the posted form data from within the controller?
My HTML Form:
<form id="contact_form" role="form" action="{{ path('submit_query') }}" method="post">`
<div class="panel-body">
<fieldset>
<div class="form-group">
<label for="name" class="control-label">Name</label>
<input type="text" class="form-control" id="name" placeholder="Full Name" data-validation-error-msg="Please enter your full name" data-validation="length" data-validation-length="min1">
</div>
<div class="form-group">
<label for="email" class="control-label">Email Address</label>
<input type="email" class="col-sm-3 form-control" id="email" placeholder="Email Address" data-validation-error-msg="Please enter a valid email address" data-validation="email length" data-validation-length="min1">
</div>
<div class="form-group">
<label for="number" class="control-label">Contact Number</label>
<input type="text" class="form-control" id="number" placeholder="Contact Telephone Number">
</div>
<div class="form-group">
<label for="subject" class="control-label">Subject</label>
<input type="text" class="form-control" id="subject" placeholder="The subject of your query" data-validation-error-msg="Please enter a subject for your query" data-validation="length" data-validation-length="min1">
</div>
<div class="form-group">
<label for="query" class="control-label">Query</label>
<textarea class="form-control" id="query" rows="5" placeholder="Please enter a detailed description of your query" data-validation-error-msg="Please enter your query description" data-validation="length" data-validation-length="min1"></textarea>
</div>
</fieldset>
</div>
<div class="panel-footer clearfix text-center"><button type="submit" class="btn btn-default">Submit Query</button></div>
</form>
Controller:
When I try:
public function submitQueryAction(Request $request)
{
$data = $request->request->all();
die(var_dump($data));
}
I get an empty array in "$data".
When I try:
public function submitQueryAction()
{
$data = $this->getRequest()->request->all();
die(var_dump($data));
}
I get a vardump of a Request object, but none of the data is mine. I have also tried the solution presented by Access POST values in Symfony2 request object for getting post values without using an object or entity, but I get an error "Call to undefined method Symfony\Component\Form\Form::bindRequest()".
PLEASE HELP.
Thank you in advance.
You are missing the name html attribute for your inputs.
If an element of the form misses this attribute, then its data will not be sent.
From w3.org :
Every successful control has its control name paired with its current value as part of the submitted form data set. A successful control must be defined within a FORM element and must have a control name.
Related
New to php, would appreciate your help with this:
I made a signup form script to validate the user's input via multiple error handlers. (check valid email, pwd and pwd re-entry match etc).
In case the user filled all fields but one had an error (failed to pass the error handler), i wanted to send back the other fields to the same form so the user doesn't have to refill'm all over again. So if the passwords dint match, i wanted to reload the same page but with the other filed filled.
i can see the information in the url of the page but not in the form fields.
below my form HTML
<div class="register-content">
<form action="includes/signup.inc.php" method="POST" class="margin-bottom-0">
<label class="control-label">Name <span class="text-danger">*</span></label>
<div class="row row-space-10">
<div class="col-md-6 m-b-15">
<input type="text" name="uFirst" class="form-control" placeholder="First name" required />
</div>
<div class="col-md-6 m-b-15">
<input type="text" name="uLast" class="form-control" placeholder="Last name" required />
</div>
</div>
<label class="control-label">Username <span class="text-danger">*</span></label>
<div class="row m-b-15">
<div class="col-md-12">
<input type="text" name="uName" class="form-control" placeholder="Username" required />
</div>
</div>
<label class="control-label">Email <span class="text-danger">*</span></label>
<div class="row m-b-15">
<div class="col-md-12">
<input type="text" name="mail" class="form-control" placeholder="Email address" required />
</div>
</div>
<label class="control-label">Password <span class="text-danger">*</span></label>
<div class="row m-b-15">
<div class="col-md-12">
<input type="password" name="pwd" class="form-control" placeholder="Password" required />
</div>
</div>
<label class="control-label">Re-enter Password <span class="text-danger">*</span></label>
<div class="row m-b-15">
<div class="col-md-12">
<input type="password" name="pwd-repeat" class="form-control" placeholder="Re-enter Password" required />
</div>
</div>
Below my php code
<?php if(isset($_POST['signup-submit'])) {
require 'dbh.inc.php';
$firstName=$_POST['uFirst'];
$lastName=$_POST['uLast'];
$userName=$_POST['uName'];
$email=$_POST['mail'];
$password=$_POST['pwd'];
$passwordRepeat=$_POST['pwd-repeat'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/", $username)) {
header("location: ../signup.php?error=invalidemail&uid&uFirst=".$firstName."&uLast=".$lastName);
exit();
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("location: ../signup.php?error=invalidemail&uFirst=".$firstName."&uLast=".$lastName."&uName=".$userName);
exit();
} else if (!preg_match("/^[a-zA-Z0-9]*$/", $username)) {
header("location: ../signup.php?error=invaliduid&uFirst=".$firstName."&uLast=".$lastName."&mail=".$email);
exit();
} else if ($password !== $passwordRepeat) {
header("location: ../signup.php?error=passwordnotmatching&uFirst=".$firstName."&uLast=".$lastName."&uName=".$userName."&mail=".$email);
exit();
?>
There are several ways to address this. Ultimately, there are two high-level options:
Pass the valid values back into the new form
Never remove the valid values(i.e. JavaScript + AJAX)
With your current setup, (1) would be simpler. To work with your current design, you would need to store the values somewhere to pass back to the form to render. The simplest would be to add them to the URL parameters(query string), but other options include cookies or session storage.
The simplest option would be to combine your form and validation into a single endpoint rather than separating them. That way, you already have the post data when rendering the form with the error messages.
Once you have the values, you can simply insert them into the form HTML with the value attribute(be sure to HTML encode(htmlentities) any user input values to avoid XSS vulnerabilities).
For example:
<input type="text" name="uFirst" class="form-control" placeholder="First name" value="<?= htmlentities($firstName) ?>" required />
I just noticed(from one of the comments) that you are already passing your valid values in the query string with your existing redirect. In that case, you can simply do something like this:
<input type="text" name="uFirst" class="form-control" placeholder="First name" value="<?= htmlentities($_GET["uFirst"]??"") ?>" required />
Encoding the values is very important. Not properly encoding values, especially from user input, can allow malicious users to craft values that break out of your HTML and alter the page, a vulnerability known as Cross-Site Scripting(or XSS, for short).
I have a problem, I am trying to make some forms in bootstrap however it messed up.
Once I converted the forms to bootstrap related they are no longer doing the job they're supposed to do.
What I am trying to do is to save form logs to a txt file, but they won't save.
When I add name="test" it won't work, instead it writes in the url.
URL: localhost/save.php?John
save.php
<?php
$myfile = fopen("test.txt", "a+");
$txt = "Name : ".$_POST['test451']." -> Surname: ".$_POST['loki'];
fwrite($myfile, $txt);
fclose($myfile);
?>
index
<form action="/save.php" class="needs-validation" novalidate>
<div class="row">
<div class="col-md-6 mb-3">
<label for="firstName">First name</label>
<input type="text" class="form-control" id="firstName" name="loki" placeholder="" value="" required>
<div class="invalid-feedback">
Valid first name is required.
</div>
</div>
<div class="col-md-6 mb-3">
<label for="lastName">Last name</label>
<input type="text" class="form-control" id="lastName" name="test451" placeholder="" value="" required>
<div class="invalid-feedback">
Valid last name is required.
</div>
</div>
</div>
</form>
Seeing the comment you left with this code: (edit: you added that in the question just now in an edit)
<form action="/save.php" class="needs-validation" novalidate>
Forms default to a GET method if there is no POST implied. So you're getting the ?John back because of it.
Add method="post" in your form.
I have a basic HTML/PHP web form. Everything works fine when I fill out all fields, except I want to make the file upload optional, not required. I have taken "required" off of the form html for the upload. I checked my handler.php and it does not say that field is required. I checked the formhandler.php and it says that attachments are null. I have looked through similar questions, but any of the more complex solutions I am probably implementing incorrectly. I've expended my knowledge of php looking for a solution. What am I missing?
Here is the html of the form:
<div class="row pb6">
<div class="col-md-6 offset-md-3">
<form role="form" method="post" id="reused_form" enctype="multipart/form-data" >
<div class="form-group">
<label for="name"> Name:</label>
<input type="text" class="form-control" id="name" name="name" required maxlength="50">
</div>
<div class="form-group">
<label for="email"> Email:</label>
<input type="email" class="form-control" id="email" name="email" required maxlength="50">
</div>
<div class="form-group">
<label for="tel"> Phone: </label>
<input type="tel" class="form-control" id="tel" name="tel" maxlength="50">
</div>
<div class="form-group">
<label for="name"> Message:</label>
<textarea class="form-control" type="textarea" name="message" id="message" placeholder="We want to hear all about your performance! Also, please include the date you need the music." maxlength="6000" rows="7"></textarea>
</div>
<div class="form-group">
<label for="file">File Upload (optional)</label>
<input type="file" class="form-control" id="image" name="image">
</div>
<button type="submit" class="btn btn-lg btn-success pull-right" id="btnContactUs">Post It! →</button>
</form>
<div id="success_message" style="width:100%; height:100%; display:none; "> <h3>Sent your message successfully!</h3> </div>
<div id="error_message" style="width:100%; height:100%; display:none; "><h3>Error</h3>We are very sorry. There was an error sending your form. Email us and we will send you a free demo.</div>
</div>
</div>
</div>
And here is the handler.php:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
/*
Tested working with PHP5.4 and above (including PHP 7 )
*/
require_once './vendor/autoload.php';
use FormGuide\Handlx\FormHandler;
$pp = new FormHandler();
$validator = $pp->getValidator();
$validator->fields(['name','email','tel'])->areRequired()->maxLength(50);
$validator->field('email')->isEmail();
$validator->field('message')->maxLength(6000);
if($_FILES['image']){ $pp->attachFiles(['image']); }
$pp->sendEmailTo('email'); //
echo $pp->process($_POST);
after code edit:
1)Chrome and Firefox will send form, Safari will not.
2)All browsers show a perpetual "Sending" message, and do not show a success or failure message for the form.
3) Forms send WITH attachments will not send the form with attachment to email, only the form alone.
You are trying to attach the image whether it exists or not with $pp->attachFiles(['image']);. You should first check if it does indeed exists and only attach it if it does like so:
if($_FILES['image']){
$pp->attachFiles(['image']);
}
So, I have my SPA at about 98% functional. The app pulls data from a MySQL database and allows the user to edit/delete records. For the page in question, it will edit/delete data of the specified student ID but it will not properly display the data in the text fields.
If you do not input a value it will display the first item in the JSON array but not the one you specify in the search field.
I did not do a very good job at explaining that but here is the HTML page that uses a function to pass data to the controller which then selects the corresponding student by ID and assigns it to the variable $scope.student. I then try to display the student data on the HTML page by using student.first_name (or any property) but it does not work correctly.
<h3>Edit/Delete Student with ID: {{student.student_id}}</h3>
<div class="form-group">
<label for="sid">Student ID:</label>
<input type="text" class="form-control" id="sid" ng-model="sid">
</div>
<p><button type="button" class="btn btn-primary" ng-click="getRecord(sid)">
Get Student Info </button> </p>
<div class='row'>
<div class="col-md-6">
<div class="form-group">
<label for="first_name">First Name:</label>
<input type="text" class="form-control" id="first_name" ng-model="student.first_name">
</div>
<div class="form-group">
<label for="last_name">Last Name:</label>
<input type="text" class="form-control" id="last_name" ng-model="student.last_name">
</div>
<div class="form-group">
<label for="hrs_completed">Hrs Completed:</label>
<input type="text" class="form-control" id="hrs_completed" ng-model= "student.hrs_completed">
</div>
<div class="form-group">
<label for="hrs_attempted">Hrs Attempted:</label>
<input type="text" class="form-control" id="hrs_attempted" ng-model= "student.hrs_attempted">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="gpa_points">GPA Points:</label>
<input type="text" class="form-control" id="gpa_points" ng-model= "student.gpa_points">
</div>
<div class="form-group">
<label for="major">Major:</label>
<input type="text" class="form-control" id="major" ng-model="student.major">
</div>
<div class="form-group">
<label for="advisor_id">Advisor ID:</label>
<input type="text" class="form-control" id="advisor_id" ng-model="student.advisor_id">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="email" ng-model="student.email">
</div>
</div>
<button type="button" class="btn btn-primary" ng-click="updateRecord()">Update</button>
<button type="button" class="btn btn-primary" ng-click="deleteRecord()">Delete</button>
And here is my controller on my Javascript page:
app.controller('editCtrl', function($scope, $http) {
$http.get("getStudentData.php")
.then(function (response) {
$scope.students = response.data;
});
$scope.getRecord = function(sid) {
id = sid;
$scope.student = $scope.students.find(s=>s.id == sid);
};
Do I need to make a seperate GET request to the server for this to work properly or do I just need to reference the student object differently?
I think there is mismatch in what you are getting as response.data and what you are trying to .find() and then what you are binding on html.
Check this plunkr.
You are trying to render by searching id property.
$scope.students.find(s=>s.id == sid);
where as you are rendering on UI using student_id property.
{{student.student_id}}
So, surely there is mismatch in what you are getting as response.data and what you are rendering using $scope.student properties. I think my plunkr will show that your function is correct.
In case this answer doesn't work, share your response.data.
I'm using symfony 2.8, I'm submitting a registration from to registerAction method. I'm getting all my submitted data like this when I use $form-getdata() in registerAction method.
AppBundle\Entity\User Object
(
[id:AppBundle\Entity\User:private] =>
[name:AppBundle\Entity\User:private] => testname
[email:AppBundle\Entity\User:private] => test#test.com
[roles:AppBundle\Entity\User:private] => Admin User
[plainPassword:AppBundle\Entity\User:private] => 123456
[password:AppBundle\Entity\User:private] =>
)
I have used $request->request->get('name') to get single name value but it is showing blank screen and printing nothing.
My html form looks like this on viewing source code in browser.
<form name="user" method="post" novalidate="novalidate">
<div class="form-group">
<div><label for="user_name" class="required">Name</label><input type="text" id="user_name" name="user[name]" required="required" class="form-control" /></div>
</div>
<div class="form-group">
<div><label for="user_email" class="required">Email</label><input type="email" id="user_email" name="user[email]" required="required" class="form-control" /></div>
</div>
<div class="form-group">
<div><label for="user_roles" class="required">Roles</label><select id="user_roles" name="user[roles]" class="form-control" style="margin:5px 0;"><option value="Normal User">Normal User</option><option value="Admin User">Admin User</option></select></div>
</div>
<div class="form-group">
<div><label for="user_plainPassword_first" class="required">Password</label><input type="password" id="user_plainPassword_first" name="user[plainPassword][first]" required="required" class="form-control" /></div>
</div>
<div class="form-group">
<div><label for="user_plainPassword_second" class="required">Repeat Password</label><input type="password" id="user_plainPassword_second" name="user[plainPassword][second]" required="required" class="form-control" /></div>
</div>
<div><button type="submit" id="user_Register" name="user[Register]" class="btn btn-success form-control">Register</button></div><input type="hidden" id="user__token" name="user[_token]" value="epZFHVctxHFlsnxG-H4OdS92DmGVjP1DDF-bKJrV2Ss" />
</form>
How can I get single posted form value.?
If $request->request->get('{form_name}') returns an array with your form data, then you can access the specific input field with $request->request->get('user')['name']. But you should use form classes instead, where you can define all of necessary fields with validation constraints, etc. Hope this helps!