Populating dynamic html elements on validation failure in Laravel 5.1 - php

In my form, I am populating state and city dropdowns using ajax.
Also, on the same form the user can add multiple employees by clicking on the "Add more button".
In both above scenarios the HTML DOM elements are generated using jquery.
I need re-build the dynamically generated elements in case the validation fails on form submit.
Can anyone please tell me a right approach for achieving the above mentioned issue.
Thanks.

Say you've generated a list of inputs dynamically by calling a js function, maybe something like
//JS
function generate(){
$("#container-abc").append("<input name=name[]>");
}
<!--HTML -->
<input name=name[] />
<input name=name[] />
Submit them and if there's validation error you will get back the values using:
//in your blade
$name = Request::old('name');
#if(count($name) > 0)
for (var i = 1; i <= {{count($name)}}; i++) {
generate();
}
#endif

you can use
return Redirect::back()->withInput();
or for more info visit https://laravel.com/docs/5.2/requests#old-input
Old Input
Laravel allows you to keep input from one request during the next
request. This feature is particularly useful for re-populating forms
after detecting validation errors. However, if you are using Laravel's
included validation services, it is unlikely you will need to manually
use these methods, as some of Laravel's built-in validation facilities
will call them automatically. Flashing Input To The Session
The flash method on the Illuminate\Http\Request instance will flash
the current input to the session so that it is available during the
user's next request to the application:
$request->flash();
You may also use the flashOnly and flashExcept methods to flash a
sub-set of the request data into the session:
$request->flashOnly(['username', 'email']);
$request->flashExcept('password');
Flash Input Into Session Then Redirect
Since you often will want to flash input in association with a
redirect to the previous page, you may easily chain input flashing
onto a redirect using the withInput method:
return redirect('form')->withInput();
return redirect('form')->withInput($request->except('password'));
Retrieving Old Data
To retrieve flashed input from the previous request, use the old
method on the Request instance. The old method provides a convenient
helper for pulling the flashed input data out of the session:
$username = $request->old('username');
Laravel also provides a global old helper function. If you are
displaying old input within a Blade template, it is more convenient to
use the old helper. If no old input exists for the given string, null
will be returned:

Related

laravel - get attribute from html tag

So I have a form in my view:
{{Form::file('projectPicture', ['class' => 'uploadedImage', 'data-some-attribute' => ''])}}
with the attribute data-some-attribute.
And in my route I retrieve it like so:
$request->file('projectPicture');
How do I get a data-some-attribute in the route? Is it even possible?
I know I can use ajax to pass any data, but can it be avoided in this case?
Thank you!
It is not possible how you intend it to work, only because it's not how form data is working under the hood. The second argument in your sample Form::file is just decorating the rendered form element. It has no correlation with the form data that is transferred between the server and client.
For all intents and purposes form data is just a glorified set of key value pairs. If you wanted to pass some-data-attribute to your route controller, you have two options -
Add another form field, and make it empty using Form::hidden. In this case, you would just name the field some-data-attribute.
If your form is submitted through a POST method, you can tack on some-data-attribute onto the form's route and retrieve it from the request.
ie - your/route becomes your/route?some-data-attribute=whatever, and you can retrieve it later with something like $request->input('some-data-attribute').

Submit form to different action with typo3 flow

I have a page with a form for creating users. A user has an hobby, which can be created on the same page by clicking on the second button which opens the page for creating a hobby. After creating the hobby, the previous user form should be shown with the user input inserted before going to the hobby page.
Is there a way to do something like with typo3 flow / fluid without using AJAX?
I tried to submit the input to a different action by clicking on the createHobby button --> The action redirects to the new hobby page, where the user can create the hobby and after creation it should redirect back to the user form with the already filled out input fields by the user .
I used...
<input type='submit' value='Create' formaction='/hobby/create' />`
to achive this, but it seems there are some problems with the uris... I get following error:
#1301610453: Could not resolve a route and its corresponding URI for the given parameters.
I think the using the attribute formaction is not a good solution for every case, as it is not supported by IE < 10 as you can see here. I think a JavaScript backport should also be considered (dynamically change the action attribute of the form when clicking on the second button, before actually submitting the form).
Concerning your error, you should not – and probably never – use direct HTML input, instead try to focus on Fluid ViewHelpers, which allow TYPO3 to create the correct HTML input.
Try this instead:
<f:form.submit value="Create" additionalAttributes="{formaction: '{f:uri.action(controller: \'hobby\', action: \'create\')}'}" />
You can make an $this->forward(...) in an initializeActiondepending on an param of your action.
Lets imagine your default Form action is "create". So you need an initializeCreateAction:
public function initializeCreateAction()
{
if ($this->arguments->hasArgument('createHobby')) {
$createHobby = $this->request->getArgument('createHobby');
if ($createHobby) {
$this->forward('create', 'Hobby', NULL, $this->request->getArguments());
}
}
}
Now you must name your input createHobby and assign your createAction this param:
In fluid:
<f:form.button type="submit" name="createHobby" value="1">Create Hobby</f:form.button>
In your Controller:
public function createAction($formData, $createHobby = false)
{
...
}
can you explain something more ... what you show has nothing to do with typo3, I don't know where you inserted that, what version of typo3 , using any extension extra ?

How to send info on HTML elements via POST?

I want to send the properties of HTML elements as data via POST, for example whether an element is visible or not?
You cannot do it with PHP and HTML alone, since the HTML form would only post a form input's name. You would need to add some JavaScript, which at the time the form is submitted, would iterate over all its inputs and modify their values to include the attribute values as well.
Example:
yourform.onbeforesubmit = function() {
// Loop over form elements and append -visible or -hidden to its value based on CSS style
// jQuery selectors like .is(":visisble") would help a lot here.
// This is just a basic example though - it would require an explicit visibility CSS rule on each
// input element...
for (var i=0; i<yourform.elements.length; i++) {
yourform.elements[i].value = += "-" + yourform.elements[i].style.visibility;
}
}
Another method would be rather than to modify the values of the inputs themselves, keep a hidden input for each visible user input and set the attributes as the value to the hidden input rather than the visible input.
You can not do this with PHP. You will need to use Javascript to determine this information and then either send an Ajax Request or add this information to an existing form.
To elaborate a bit more: PHP is executed Server Side and then sent to the Client (Browser). The Server is not aware of the state of the HTML Elements in the Browser.
As far as i can tell you have a form that is submitted anyway? So add a piece of javascript which is called before the form is submitted (onsubmit property of the form) and have it read out the status of the elements (visible, hidden, ...) and set this information to some hidden form fields.
Make sure the javascript that is called before the form is submitted is returning true, otherwise the action gets cancelled.
In ajax.
Try Prototype Framework, it is really easy to use!
http://prototypejs.org/api/ajax/request
If you want to do that I suppose you will have to create some hidden fields and javascript that would fill them in with information depending on your elements attributes. As far as I know there is no other way.
You have to define your data definition standard first: what do you want to store, and under what name.
then, imho you have to serialize the result and send it through POST, for finally unserializing it once at the server.
Use JSON serialization for an effective way of proceeding.
Include Hidden inputs using PHP like the following:
<input type="hidden" id="hidden1" name="hidden1" value="<?php if(condition) echo "default"; else echo "default";?>">
This default value can be set by PHP during page load, for transferring extra hidden data from one page load to another. But can also be modified by javascript after page load:
<script type="text/javascript">
document.getElementById("hidden1").value="true";
</script>
Note: PHP can change the value of any hidden or non-hidden element only during the next page load. It doesn't have any control over the HTML it sends to the browser. This is why you need Javascript(Client side scripting).

Add and remove form fields in Cakephp

Im looking for a way to have a form in cakephp that the user can add and remove form fields before submitting, After having a look around and asking on the cake IRC the answer seems to be to use Jquery but after hours of looking around i cannot work out how to do it.
The one example i have of this in cake i found at - http://www.mail-archive.com/cake-php#googlegroups.com/msg61061.html but after my best efforts i cannot get this code to work correctly ( i think its calling controllers / models that the doesn't list in the example)
I also found a straight jquery example (http://mohdshaiful.wordpress.com/2007/05/31/form-elements-generation-using-jquery/) which does what i would like my form to do but i cannot work out how to use the cakephp form helper with it to get it working correctly and to get the naming correct. (obviously the $form helper is php so i cant generate anything with that after the browser has loaded).
I an new to cake and have never used jQuery and i am absolutely stumped with how to do this so if anyone has a cakephp example they have working or can point me in the right direction of what i need to complete this it would be very much appreciated.
Thanks in advance
I would take the straight jquery route, personally. I suppose you could have PHP generate the code for jquery to insert (that way you could use the form helper), but it adds complexity without gaining anything.
Since the form helper just generates html, take a look at the html you want generated. Suppose you want something to "add another field", that when clicked, will add another field in the html. Your html to be added will be something like:
<input type="text" name="data[User][field][0]" />
Now, to use jquery to insert it, I'd do something like binding the function add_field to the click event on the link.
$(document).ready( function() {
$("#link_id").click( 'add_field' );
var field_count = 1;
} );
function add_field()
{
var f = $("#div_addfield");
f.append( '<input type="text" name="data[User][field][' + field_count + ']" />' );
field_count++;
}
Of course, if a user leaves this page w/o submitting and returns, they lose their progress, but I think this is about the basics of what you're trying to accomplish.
This was my approach to remove elements:
In the view, I had this:
echo $form->input('extrapicture1uploaddeleted', array('value' => 0));
The logic I followed was that value 0 meant, not deleted yet, and value 1 meant deleted, following a boolean logic.
That was a regular input element but with CSS I used the 'display: none' property because I did not want users to see that in the form. Then what I did was that then users clicked the "Delete" button to remove an input element to upload a picture, there was a confirmation message, and when confirming, the value of the input element hidden with CSS would change from 0 to 1:
$("#deleteextrapicture1").click(
function() {
if (confirm('Do you want to delete this picture?')) {
$('#extrapicture1upload').hide();
// This is for an input element that contains a boolean value where 0 means not deleted, and 1 means deleted.
$('#DealExtrapicture1uploaddeleted').attr('value', '1');
}
// This is used so that the link does not attempt to take users to another URL when clicked.
return false;
}
);
In the controller, the condition $this->data['Deal']['extrapicture1uploaddeleted']!='1' means that extra picture 1 has not been deleted (deleting the upload button with JavaScript). $this->data['Deal']['extrapicture1uploaddeleted']=='1' means that the picture was deleted.
I tried to use an input hidden element and change its value with JavaScript the way I explained above, but I was getting a blackhole error from CakePHP Security. Apparently it was not allowing me to change the value of input elements with JavaScript and then submit the form. But when I used regular input elements (not hidden), I could change their values with JavaScript and submit the form without problems. My approach was to use regular input elements and hide them with CSS, since using input hidden elements was throwing the blackhole error when changing their values with JavaScript and then submitting the form.
Hopefully the way I did it could give some light as a possible approach to remove form fields in CakePHP using JavaScript.

Is there a built in way in Zend-Form to hide the value of the SUBMIT input field?

If I build a form:
$search_words = new Zend_Form_Element_Text('text');
$search_words->setRequired(true)->setDecorators(array(array('ViewHelper')));
$form->addElement($search_words);
$go = new Zend_Form_Element_Submit('gogogo');
$go->setDecorators(array(array('ViewHelper')))
->setIgnore(true);
$form->addElement($go);
With method GET.
I will see in the URL gogogo=gogogo. If I was writing the markup myself, I simply wouldn't give the submit any [name] attribute and that would have solved that. Trying to set the name of a submit to '' won't work (either throws an exception or is being ignored, depends on the way you do it).
Any (built in) ideas?
Another possibility would be to disable the submit button before the form is submitted:
$go->setDecorators(array(array('ViewHelper')))
->setIgnore(true)
->setAttrib('onclick', 'this.disabled = true');
This way, the value of the submit button will be ignored upon submitting the form.
There are a few possible options:
Use a custom decorator to build the markup, so a name attribute is not specified
Use a string replacement function on the markup returned by Zend_Form's render methods, to remove the attribute
What I often do, as follows
I usually add a custom route so that either of the following is valid:
domain.tld/search/keyword
domain.tld/search?q=keyword
Then you can use javascript to redirect to the cleaner form of the URL, taking care to urlencode the keyword field
Most of your users will see the cleaner URL this way.

Categories