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.
Related
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 ?
I need to make a form where client information can be added by people at the administration department. On the first form page, information like client name, address and contact details can be entered, as well as whether or not the client has children.
The form gets validated by PHP. If the client does not have children, the data is saved to the database. If the client does have children, the form data gets saved in hidden form fields, and a second form page is shown, where up to 10 children and can be added.
However, on initial page view, only one text input is visible. With a javascript button, more text input fields can dynamically be added (until the limit of 10 is reached).
The problem is the validation in PHP. If one of the text inputs contains a non-valid string, the form should be re-displayed with the right number of fields, and those containing errors in a special HTML class (in the CSS i give that class a red border for usability reasons, so the user can immediately see where the error resides). However, because the adding of fields happens with Javascript, the form gets re-displayed with only one field.
Any ideas on how to address this problem are very welcome. I'm proficient in PHP, but JavaScript is very new to me, so I'm not able to make big changes to the script i found to dynamically add fields.
I've dealt with something similar in the past. There are a couple of options that come to mind.
Since you have JS code to generate new fields at the click of the button, why not expand that JS function so it can also be called with some parameters passed. If there are parameters, it will populate the fields with existing data.
Then, if the form is being re-displayed due to errors, or for editing, from PHP, pass some information to Javascript so that when the page loads, you create the fields and populate them with data.
To illustrate, I assume you have something like this:
Add Another Child
And you have the function:
function addNewFormField() {
// create new HTML element to contain the field
// create new input, append to element container
// add container to DOM
}
Change it so it is like this:
function addNewFormField(data) {
// create new HTML element to contain the field
// create new input, append to element container
// add container to DOM
if (data != undefined) {
newFormElement.value = data.value;
newContainerElement.class = 'error';
}
}
And from PHP, add some code that runs onload:
<script type="text/javascript">
window.onload = function() { // replace me with jQuery ready() or something proper
<?php foreach($childInList as $child): ?>
addNewFormField({ value: '<?php echo $child['name'] ?>' });
<?php endforeach; ?>
}
</script>
Hope that helps, its a high level example without knowing exactly how your form works but I've used similar methods in the past to re-populate JS created fields with data from the server side.
EDIT: Another method you could use would be to create the HTML elements on the PHP side and pre-populate them from there, but that could end up with duplicate code, HTML generation from JS and HTML generation of the same stuff from PHP. As long as the JS side was smart enough to recognize the initial fields added by PHP you can go with whatever is easiest to implement. Personally I'd just extend your JS code to handle optional data like illustrated above.
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).
In PHP, in a particular CMS I am using a custom field, which works like google suggest.
As in, for each letter I type an SQL query is performed and matching records are displayed. When clicking on a record it fills the field with that record.
I am fairly certain this is all done with JavaScript.
I need to know how I can access the resultant content of that field, with the text placed through JS, before it is submitted so I can explode() it.
The CMS I am using is using mootools, so a solution relying on mootools would be ideal.
(This answer assumes that you have control over the markup of your forms (the form that requires a string "explosion" before submit) and/or you feel comfortable tinkering with whatever plugins you're using.)
first, make sure that you aren't submitting your form using an actual submit button (). We'll need to submit the form using javascript after fiddling with the field's contents.
next, make sure that your input box (the one you're grabbing text from) and your hidden inputs have unique ids. This will make it easier to query the DOM for the data we need.
Inside your form, in place of a "real" submit button, create a form button:
<form action="something.php" name="myform">
<input type="hidden" id="hiddenItem">
// SOME STUFF
<input type="text" id="autocomplete_field" value="whatever"/>
// SOME OTHER STUFF
<input type="button" value="Submit" onclick="processForm(this)"/>
</form>
Then, write a javascript function to process the string and submit the form:
processForm = function(el){
text = $('autocomplete_field').get('value');
// Lets assume the strings separates words (what you're exploding apart) using spaces
// something like 'DOGS CATS BIRDS PETS'
var array = text.split(' ');
// returns ['DOGS','CATS','BIRDS','PETS']
$('hiddenItem').set('value',array[0]);
// #hiddenItem now has the value 'dogs'
//SUBMIT THE FORM
el.getParent('form').submit();
};
Hope this helps!
You could try to use JS to send the field on some event (onkeyup?) to your php script. After it does it's part, store the result as a session variable and you can retrieve that later.
Try using jquery's get function.
Was that your question?
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.