sending a value to an input using Symfony - javascript

I am trying to use javascript inside Symfony and then I got a problem. The problem is located at my file twig.html. At the begining I had this code:
{{ form_widget(form.name, {'attr': {'class': 'form-control'} }) }}
Then I change it to this in order to use dynamic validation(that was the same code generated in browser, I just add onkeyup action)
<input type="text" id="person_name"
onkeyup="myFunction()" name="person[name]" required="required"
class="form-control" />
Then I was happy because my validation rules work, but I discovered that when I want to update to form. The field name is empty (but in the server it's good). So I would like to get this field. In my function updateAction I dump variable person before handling the form and then name was containing the good element. So the problem is there is a difference between form_widget and the good I just did. I would like to do a thing like this to get my field name:
<input type="text" id="person_name"
onkeyup="myFunction()" name="person[name]" required="required"
class="form-control" value="if(form.name is not empty) form.name"/>
Thank you.

Are you passing the entity or document to your createForm function?
Something like that should work:
controller
$em = $this->getDoctrine()->getManager();
$your_entity = $em->getRepository(**your_entity_path**)->findOneBy([**parameters**]);
$edit = 1;
if(!isset($your_entity)) {
$your_entity = new Your_entity();
$edit = 0;
}
$form = $this->createForm(**your_entity_type_path**, $your_entity);
$editForm->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if(!$edit)
$em->persist($your_entity);
$em->flush();
//other code
}
I hope this is not too messy

Related

Passing item value from model to JS - MVC C#

Im working on a project with MVC and i'd like to know if there's a way to store the id of an input, which is a value received from one of my model items, into one of my JS variables
here's how the id of the input is being adressed
#foreach (var item in Model) {
<input type="hidden" value="#item.id" id="#item.id">
<input type="hidden" value="#item.nome" id="#item.nome">
<input type="hidden" value="#item.preco" id="#item.preco">
}
and here's what i been trying to do in my .JS file
var id = document.getElementById('#item.id').value;
var nome = document.getElementById('#item.nome').value;
var preco = document.getElementById('#item.price').value;
You can use css class to mark elements where you want to store the id
select all elements with that css class using js
read id attribute for each element using loop
store it the way you need, eg. an array
Well, if you try this you see that your values are saved.
let id = document.getElementById('Id').value;
let name = document.getElementById('Name').value;
let price = document.getElementById('Price').value;
console.log(id);
console.log(name);
console.log(price);
but i somehow fail to use them in html. This doesn't work for example.
<script>
document.getElementById('Id').innerHTML = id;
document.getElementById('Name').innerHTML = name;
document.getElementById('Price').innerHTML = price;
</script>
<h1 id="Id"></h1>
<h1 id="Name"></h1>
<h1 id="Price"></h1>
It's maybe because the input is hidden.
Method 1
Well you can just expose that item ID directly to JavaScript
<script>
// this must be in the .html file, using window makes the variable global
// most rendering frameworks don't do conditional/server side rendering on static js files
window.ITEM_DATA = {
itemId: "#item.id"
}
</script>
<input type="hidden" value="#item.id" id="#item.id">
<input type="hidden" value="#item.nome" id="#item.nome">
<input type="hidden" value="#item.preco" id="#item.preco">
Method 2
Alternatively, you can give each input a class and select all of the classes (or all of the inputs with type hidden)
<input type="hidden" value="#item.id" id="#item.id" class="item-data">
<input type="hidden" value="#item.nome" id="#item.nome" class="item-data">
<input type="hidden" value="#item.preco" id="#item.preco" class="item-data">
// this could be in its own file because we aren't relying on the server
// this is client-side js
const [itemId, itemNome, itemPreco] = document.querySelectorAll(".item-data")
// this could also fit a narrow use case
// document.querySelectorAll("input[type='hidden']")
Edit: added clarification to method 2
you can access model directly in razor page like #ModelName.objectname but you should import model like
#model ModelName
example : #Model.id

How to populate an textboxes with query string value(s) from URL

I have a simple Window Forms application that opens up a webpage with set parameters.
The link send the user to a page with 2 text box fields and a submit button.
I am trying to automate this process so it grabs the parameter values and puts it into the text box then clicks submit .
This is my current code for my windows form:
using System;
using System.Windows.Forms;
using System.Diagnostics;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
libLink.Links.Remove(libLink.Links[0]);
libLink.Links.Add(0, libLink.Text.Length,
"http://www.example.com/?UserName=value1&FirstName=value2");
}
private void libLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
ProcessStartInfo sInfo = new ProcessStartInfo(e.Link.LinkData.ToString());
Process.Start(sInfo);
}
}
}
How can I create a script that that takes those parameters in the URL to populate two text box fields and then submit the form?
This is my HTML Page:
<form action="/send" method="post" novalidate="novalidate">
<input class="form-control" data-val="true" data-val-UserName="Wrong username" data-val-required="Enter a valid Username" id="Username" name="Username" placeholder="Username" type="text" value="">
<input class="form-control" id="FirstName" name="FirstName" placeholder="First Name" type="text" value="">
<button type="submit">Sign In</button>
</form>
Fairly new to coding so I tried to keep my code as simple as possible.
I looked at possible methods such as QueryStrings, JavaScript and Jquery, but I am not sure how to approach this problem.
There's a few ways of doing it really but i'll give you a basic walk through of how i would do it in javascript with a bit of JQuery.
we have variable with the URL we start by:
var url = "http://www.example.com/?UserName=value1&FirstName=value2"
var params_string = url.split("?")[1] //UserName=value1&FirstName=value2
so first we split the string into a list like above which returns a list of the items which are separated by the "?" character, but we only need the second item(at index 1) so we add the [1] to the end to only store that bit.
We then split this again to get the individual parameters.
var params_string_list = params_string.split("&")
["UserName=value1","FirstName=value2"]
which returns a list as above, again need to break that down i would make it into an object like so :
var params = {}
for(var i =0;i < params_string_list.length;i++ ){
var temp = params_string_list[i].split("=") // looks like ["UserName","value1"]
params[temp[0]]= temp[1]
} //params now looks like {"UserName":"value1","FirstName":"value2"}
as this makes it easy to access and use.
we can then do the following to set the values in the form:
if(params.UserName){
$('#Username').val( param.UserName );
}
if(params.FirstName){
$('#FirstName').val( param.FirstName );
}
if statments are there to check that the value exists in the object so we don't sent the value to "undefined" by accident.
Hope this helps.

Input from the form is not passed to the controller and keeps being "undefined"

I have the hardest time dealing with forms and passing values from them to the controller. I have the same story every time: the ng-model and everything is set up but the controller is not accepting what I'm trying to pass it and thus gives me that the var is not defined. Would anyone suggest how to deal with this and how to properly setup forms with Angular? Their documentation is darn awful!
Here's the markup of the form:
<div>
<form name="thisForm" ng-submit="submit()" class="wa-id-submit-form">
<label>Submit your number</label>
<input name="wa_id" ng-model="submission" type="text" class="form-control" required />
<input type="submit" class="form-control" name="submit" value="Submit" />
</form>
</div>
Here's the function and the var I'm trying to pass it to:
$scope.submit = function() {
var data = {
"wa_id": $scope.wa_id
};
console.log($scope.wa_id);
var hookphp = submitIdService.submitId();
hookphp.save(data,
function(result){
console.log(result);
};
The php side of this all works just fine and doesn't need to be looked at. I just need to pass that one line from the input to the data variable and it's not. Am I not making the ng-model and such talk properly to each other?
},
function(result){
console.log('NO GO');
}
);
};
You should use corresponding ngModel to access data in controller, not input name:
var data = {
wa_id: $scope.submission
};
I have been reminded of something very important when dealing with ng-models here
The ng-model has to have a .notation in it to function properly. It's possible that it would function without it as well, but even people who help develop Angular strongly recommend using it with a "."
Here's what had to be done with my code:
<form ng-submit="submit()" class="wa-id-submit-form">
<label>Submit your number</label>
<input name="waid" ng-model="waid.submission" type="text" class="form-control" required />
<input type="submit" class="form-control" name="submit" value="Submit" />
</form>
an ng:
$scope.waid = {};
$scope.submit = function() {
var data = {
"wa_id": $scope.submission
};
var hookphp = submitIdService.submitId();
hookphp.save(data,
function(result){
console.log(result);
},
function(result){
console.log('NO GO');
}
);
};
An object had to be declared "empty" prior to being able to use it in the function as well.

How to get formData from Angular-Payments

I am using Angular-Payments that intercepts the form data and submits it to Stripe. This works well, however, I'm not sure how to access form data after its sent to stripe. For example, my form has quantity field which I would like to get access to but I don't know how to...
Here is what I'm doing HTML
<form stripe-form="handleStripe" role="form" ng-if="authenticated" name="takeMoneyForm" ng-submit="takeMoney(takeMoneyForm, model)">
<input type="text" name="card_number" ng-model="number" payments-validate="card" payments-format="card" payments-type-model="type" ng-class="takeMoneyForm.number.$card.type">
<input type="text" name="card_cvc" ng-model="cvc" payments-validate="cvc" payments-format="cvc" payments-type-model="type">
<input type="text" nam="card_expiry" ng-model="expiry" payments-validate="expiry" payments-format="expiry">
<input type="text" ng-model="quantity"/>
<button class='form-control submit-button btn btn-majoo' type='submit'>Pay ยป</button>
</form>
JS
$scope.takeMoney = function(formData, model){
$scope.handleStripe = function(status, response){
if(response.error) {
// there was an error. Fix it.
alert("Error happened")
} else {
var dataModel = {
email: model.email,
profile: {
stripe_token: response.id,
stripe_id: model.profile.stripe_id
//here I would like to get access to the quantity from the form
}
}
djangoAuth.takeMoney(dataModel)
$scope.complete = true;
}
}
}
I feel like this should be simple but I'm very new to Angular and can't seem to figure this out.
since youre using ng-model the values of those fields should be on that form's scope(as in scope.number)
If they are not accessible it could be one of two things:
1) Angular Payments clears the ng-model following submit
2) you are trying to access it from a different scope.

Dynamically duplicated forms disappear on CodeIgniter reload

I have the following code that needs to be duplicated:
<form method="post">
<div id="field-row-container">
<div id="field-row-1" class="field-row">
<div class="field-element">
<label for="Name[1]">Name</label>
<input type="text" id="Name[1]" name="Name[]" />
</div>
<div class="field-element">
<label for="Email[1]">Email</label>
<input type="text" id="Email[1]" name="Email[]" />
</div>
<hr/>
</div>
</div>
<div class="form-element">
<input type="button" class="confirm add-field-row" value="Add" />
<input type="button" class="danger delete-field-row" value="Delete" />
<input type="submit" />
</div>
The duplicated / dynamically added elements will have the same names of Name[] and Email[] but their ID's will be incremented.
The JavaScript is below, based from Josiah Ruddell's form duplication script.
var template = $('#field-row-container #field-row-1').clone();
window.addForm = function () {
var parent = $(this).closest('.dynamic-rows').attr('id');
var fieldRowCount = countRows(parent) + 1;
var newFieldRow = template.clone().find(':input').each(function () {
var newId = this.id.substring(0, this.id.length - 3) + "[" + fieldRowCount + "]";
$(this).prev().attr('for', newId); // update label for
this.id = newId; // update id and name (assume the same)
$(this).closest('.field-row').addClass('new-row');
}).end()
.attr('id', 'field-row-' + fieldRowCount)
.appendTo('#field-row-container');
}
$('.add-field-row').click(addForm);
Whenever I submit the form to CodeIgniter and if there is a validation error, once the controller reloads the multi-part form, the dynamically added elements disappear as well as the values in the initial fields.
How do I go around this problem? I'm at a loss on how to solve this...
Other notes that might help:
This is a component multi-part form with only one form controller
I have multiple instances of this - Addresses, Education Degrees and such
I use CodeIgniter's form_validation library to check server-side each array of posts
When the page with the form on reloads after the controllers redirects back to it after failing validation, it will only reload the original page, with no DOM manipulations applied.
I would perform the POST request which submits the form via ajax, so you can handle the response without leaving the page. Something like this:
$.post('/locationOfController.php', $('#yourForm').serialize(), function(response){
if(response.valid){
window.location.href = '/somewhereAfterFormPosted.php';
} else {
$('#yourForm').append("<p>"+response.error+"</p>");
}
}, 'json');
and change the controller to return a JSON object based on whether validation passed or not. To match up with my example above, you would return something like below when an error occurs:
{valid: false, error: 'Please fill out the whole form'}
Try something like that as a basic example. You could do much more, such as returning several errors if multiple fields are invalid.

Categories

Resources