checkField() doesn't check behat mink - php

I'm trying to use the checkField() for the first time, it's found the checkbox but doesn't check it.
The html:
<label>
<input class="sr-only" value="on" type="checkbox">
<span>I want an open return</span>
<label>
Look at the code:
$this->getSession()->getPage()->checkField("I want an open return");
I also try it:
$this->getSession()->getPage()->find("css", "input[type=checkbox].sr-only")->check();
Boths doesn't return any error but I can see the checkbox isn't check when I run the test.
The follow code return bool(false) as expected:
$this->getSession()->getPage()->find("css", "input[type=checkbox].sr-only")->isChecked();

checkField() might not work, because this relies on the value attribute of the element, if is true/false and you have on/off which will fail in evaluating the status of the checkbox, same thing for check().
As an alternative to check you can find the element and click():
find("css", "input[type=checkbox].sr-only")->click();
Checking if is checked with isChecked() will fail for the same reason.
You might need to do a custom validation, for example get the value of the value attribute and check it if is on or off and throw exception or return status as needed.
Things to keep in mind:
- inspect the page and check if selector is ok
- make sure the selector finds only one element, or the first element found in the list is the one you need
- make sure you wait for the element if needed
- use page objects
- the class that contains this click/check should extend the Page object and the line should look like this:
$this->find("css", "input[type=checkbox].sr-only")->click();

Finally, it's works, after change "input" to "label" using the follow code line:
$this->getSession()->getPage()->findAll("css", ".div-name
.second-div-name label")[0]->click();
My checkbox input was inside two divs, because that I have this two divs names above.
=)

Related

HTML input tag passing placeholder as value to PHP

I'm trying to implement the 'placeholder' attribute on a new mobile web site. Running into an issue where if a user leaves the field blank (showing the placeholder) then that placeholder is submitted as the field value for PHP to receive and place in the database. Instead it should (I assume) be sending an empty value. This causes problems with server side validation - the receiving PHP script thinks a legitimate value has been submitted instead of an empty value which would throw an error back to the user.
I am hoping there is a quick fix to this issue.
Sample code below:
<form action="somepage.php" method="post">
<input type="text" name="yourName" placeholder="Enter your name here">
<input type="submit">
</form>
PHP sees:
$_POST['yourName'] = 'Enter your name here';
instead of:
$_POST['yourName'] = '';
The latter is what I want it to see.
Any help would be greatly appreciated!!!
* EDIT **
Here is an example form with the problem:
https://www.badgleymischka.com/mobileTest.php
Leave all fields as is (note in the source these are filled in by the placeholders, not the values). Click the "CONTINUE" button and you will see the _POST variables with the placeholder values.
Something is removing the placeholder attr text on page load on several inputs...
Based on your source, you're calling two different jQuery scripts. Delete this found near your closing <body /> tag. This may be conflicting with Foundation's included Placeholder plugin.
<script src="js/vendor/jquery.js"></script>
But this is probably the culprit: Not sure what you're trying to write here. But this looks to be the issue. See line 17 in jquery.main.js. Remove this all. I don't think it's needed and is conflicting.
// clear inputs on focus
function initInputs() {
PlaceholderInput.replaceByOptions({
// filter options
clearInputs: true,
clearTextareas: true,
clearPasswords: true,
skipClass: 'default',
// input options
wrapWithElement: false,
showUntilTyping: false,
getParentByClass: false,
placeholderAttr: 'value' // <-- ding, ding! Prob the conflictor, if not this entire function
});
}
I cannot reproduce your error. I tested it using Firefox 25 and 26, Chrome 31, IE 11, Opera 12.16 and Safari 5.1.7. And looking at the specification I don't believe that the placeholder is intended to be submitted - so you are indeed experiencing some kind of bug.
The only reason for this behavior I can think of is that you are including a (java)script in your HTML, aimed at browsers that don't support HTML5 (and the placeholder attribute). Such a script could be filling empty inputs with their placeholders, but failing to remove them before the form is submitted.
If this is indeed the case, and your problems are caused by such a script, you can solve them by either fixing the script or removing it completely. If you choose to fix the script, you'll need to make sure that inputs whose value equals their placeholder are reset to their default value.
Just stumbled across this in my own search, so if anyone else is looking for an answer to this try this:
<input type="text" name="yourName" placeholder="Enter your name here" required>
By adding "required" to the input tag the user must fill out this field before submitting.
This should work like charm but i assume since its on mobile something is different.
One solution(i am sure there is a better one) is to check it with an if.
So if the value is the same as the place holder then make it blank and then continue your validations.
Also try to put val="".

Why doesn't set_value() work with foo[bar][x][lorem] array inputs?

So let's say i have a form where the user can add as many dogs as they want by pressing a + button.
The form is like:
Dog #1 <br/>
<input name="house[dogs][][name]" value="<?=set_value('house[dogs][0][name'])?>"/>
<input name="house[dogs][][age]" value="<?=set_value('house[dogs][0][age]')?>" />
Dog #2 <br/>
<input name="house[dogs][][name]" value="<?=set_value('house[dogs][1][name'])?>"/>
<input name="house[dogs][][age]" value="<?=set_value('house[dogs][1][age]')?>" />
On CodeIgniter, I run a form validation in order for set_value() to work as well:
$house = $this->input->post('house');
$dogs = $house['dogs'];
$i = 0;
foreach($dogs AS $dog){
$this->form_validation->set_rules("house[dogs][$i][name]", 'Dog Name', 'required');
$this->form_validation->set_rules("house[dogs][$i][age]" , 'Dog Age' , 'required');
$i++;
}
This whole thing doesn't work, How to make set_value() support array inputs like that?
Thanks in advance.
You might have to make the input name the exact same as the first parameter of set_value().
One might not be able to be [], while the other can use [0].
Very related: http://codeigniter.com/forums/viewthread/179581/ Ironically, a post I made months ago that was bumped this morning.
Also related: CodeIgniter: Validate form with multidimensional POST data
<ignore>
To make a long story short, Codeigniter does not handle indexed field names very well by default.
To simply repopulate the input and work around set_value()'s shortcomings, you can try something like this:
<?php
$value = isset($_POST['house']['dogs'][1]['age']) ? // was the value posted?
form_prep($_POST['house']['dogs'][1]['age']) : // if so, clean it
''; // if not, leave empty
?>
<input name="house[dogs][1][age]" value="<?php echo $value; ?>" />
Since you're probably using a loop to output these, I don't think it will be too much of a bother. You could populate a separate array of values and read those instead if you wish, you get the idea. set_value() automatically runs form_prep(), so that's why I added it.
I'm not too sure about the validation. You may have to do the validation yourself, which while bothersome, shouldn't be too difficult. Remember you can always run the validation methods manually. Example:
if ($this->form_validation->valid_email($this->input->post('email')) {}
You may want to just take the easy way out and change your field names to use a single index, like dog_age[], which I believe will make the validation easier for CI to handle. Best of luck, hoping for a fix one of these days in CI core.
</ignore>
EDIT: I have no idea how this escaped me, but apparently validation and set_value should in fact work as expected - not sure if this was a recent change or if the issue never really existed. I definitely remember having issues with it before, and the linked posts suggests others are too. Check out this answer though:
CodeIgniter: Validate form with multidimensional POST data
I tested it (running 2.0.2) and it does in fact work. I don't see anything in the change log, but I did test it and it did work. Make sure your on the latest version and try again perhaps, or let us know if I'm missing something here.
Like your other answer says, you probably just have to explicitly index the field names like name="house[dogs][1][name]" instead of name="house[dogs][][name]".

jquery - select all checkboxes with js array name

I want to use a JQuery "check all" function in a form like this:
http://jetlogs.org/jquery/jquery_select_all.html
My problem is I am generating my form from a php script, and I don't know exactly how many checkboxes I will have in advance.
I use the "array" naming convention to be able to get all the selected checkbox values in my $_POST data...
so my checkboxes are like that:
<input type="checkbox" name="items[]" value="<?php echo $id ?>">
but this JQuery declaration does not work:
$("input[#name=items[]]").each(function()
{
this.checked = checked_status;
});
probably because the "[]" at the end of my "items" messes up the JQuery declaration... I tried to write #name=items[] like that: "#name=items[]", and to put some anti-slash before the [ and ] so they're not considered as special characters but it didnt work...
If someone knows a solution and is willing to share it'd be great!! :)
Escape internal brackets with \\(no space) - it should fix the problem.
This selector works for me:
$('input[name=items\\[\\]]')
Try using
$('input[name="items[]"]')
No need for # and use ". Note that the selector outside quotes are '. Otherwise you might cause parse error.
First of all, your name attribute should be used to set +1 elements with the same name. It's practically the same as the id attribute and should be unique per element excepted for references, but that is not the case for you.
Try using the class attribute, it's made for the things you want to do!
another thing is that in your code, you can only set your checkboxes to 'checked', but never to uncheck, this code will set your checkboxes to checked true or false, according to what it gets as attribute from the clicked element.
you can do something like this:
set your check all checkbox with an id
<input type="checkbox" id="checkAll">
Then set on all checkboxes that should be checked/unchecked a class
<input type="checkbox" class="checked">
And the you can do something like this in jQuery
$("#checkAll").click( function(){
var checkedValue = $(this).attr("checked");
$("input.checked").attr("checked", checkedValue); });
this will change all checkboxes with class checked to the same checked attribute as the one with id checkAll
$("input[name='smsid[]']")
This code works fine for me...

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.

Validating one or the other

I've created a javascript function that allows me to validate if one field or the other is filled (called, shockingly enough, oneortheother). Essentially, it checks if neither is filled, or both, and throws an error.
One of the fields being validated is a input type="file" field. I'm displaying below the field the existing file, so that the users can see if it's the file they want.
Is there any way to still validate via oneortheother without having a value in the input type="file"? Any kind of javascript trickery?
I'm at wits end at this point, and have a demo later today that needs this functionality, so any help would be greatly appreciated.
EDIT:
As requested, here's some examples:
<label for="pdf">Upload PDF:
<span class="fieldnote">Files of type .pdf</span>
</label>
<input type="file" name="pdf" id="pdf" class="external_form_field oneortheother_url" value="/downloads/white_papers/HigherOrderPerl.pdf" />
<label>Existing file:</label><span class="preview">HigherOrderPerl.pdf</span>
<label for="url">Link to asset:</label>
<input type="text" name="url" id="url" class="external_form_field oneortheother_pdf" value="" size="25" />
Notice that the class oneortheother_url and oneortheother_pdf are applied. This allows the validation routine to know which field to compare to. The comparison is:
if (fObj.value && fObj2.value) { }
and
if (!fObj.value && !fObj2.value) { }
I unfortunately I couldn't understand the actual question, but here's a sidebar tip:
The XOR operator can come in handy (though obscure) in cases like this:
if (fObj.value ^ fObj2.value) {
// Only one value is set, we're good
} else {
// Both of them are set or neither of them are set
}
I am not sure how your validation function works, but it seems like you could add a hidden input that holds the url of the uploaded preview file OR the value in the file input. Then you could just compare the url input with the hidden input.
But it seems likely you'll just need to write a custom validation function.
I'm not sure I understand your question completely as it's not clear to me.
You want to check this:
if (fObj.value && fObj2.value) {}
and
if (!fObj.value && !fObj2.value) {}
So why not add this in as well...
if (fObj.value && !fObj2.value) {}
or
if (!fObj.value && fObj2.value) {}
What about adding a radio button next to each option, and allowing the selected radio button to determine which option is used?
I'm not sure exactly what you're trying to do here, but you could add a hidden form field, then attach a function to both the file input and the URL inputs' onchange events, that would set the hidden field to this value.
Fundamentally I'm not even sure that the approach you're currently taking is appropriate - Firefox 3, for example, doesn't let you edit the contents of a file field directly and as far as I can tell gives you no way to "unset" a value. So once a file has been chosen, the "pdf" input will always be non-null, which with the constraints you have set (as I understand them) means that the "url" input is effectively permanently disabled. This is even worse since you give the file input an initial value so that it will never ever be null/empty string.
You may need to take a step back and think about exactly what you're trying to acheive and whether an alternative technique might be better. For example, a radio button to select between the file upload box or a URL resource, which disables and enables fields as appropriate.
Additionally, the fact that most people here didn't understand quite what you're asking even after an edit is an indication that there's something about it that's not too intuitive, and it implies that people who will need to maintain this code in future might go through a similar thing. Again, refactoring the design is probably in order, or perhaps jsut a bunch of descriptive comments.

Categories