I am trying to use 'filled' on a POST request using Laravel 8 to determine if a field is blank or not.
<input type="text" name="msg" value="">
The POST array when sent contains data for this or no data, so the POST is working fine.
['msg' => 'data here..']
For a test, I am evaluating the request as follows:
if ($request->filled('msg')) {
echo 'OK';
} else {
echo 'Empty';
}
This always returns OK, regardless of whether the field has data or not. If I log the request array, the fields does indeed contain nothing.
Log:info(print_r($request->all(), true));
So, I guess my question is, how does the 'filled' method work? Am I missing something?
Many thanks.
Related
In my application I am doing client side and server side validation. Client side validation is pretty easy and user will not be able to click on the submitForm button. But suppose the zip code entered does not match with the order number and server is giving me error in 200 response in angular $http call promise. How can I show the server side error and maintain my validation ?
{"result":{"success":false,"code":null,"message":"The entered Zip does not match with Order"},"errors":
[]
Might not be the exact answer but could help :
1) On the server side if there are errors you should first stop the script from reaching to database.
2) Populate error messages on the server side in an array in the form of associative array, which can contain field name as key and error message as value. Later send the array to client side in JSON format.
3) On the client side loop through the JSON object to initialise the scope variables that will contain error messages per field.
May be in the format : serverErrors.fieldName.error = 'Error Message from server'
This should be a scope object. And the same object should be rendered on the template per field. So that when you loop through your JSON and assign error messages to each field it will show up in template. As Angular has two way binding.
This way you will be able to handle custom server side validations and show errors on client side. And this is possible not just in theory we have implemented this approach in one of our projects.
Hope that helps :)
I think you can try
$http.post('URL', { "ID": ID }).success(function (resultData) {
if (results.result.success) {
alert("scuess!");
$window.location.href = "/";
}
else {
alert(results.result.message)
}
});
I have tried all the possible approaches found, but I am struggled to get the default remote validator working.
I'm just trying to achieve to check if the mail for a registration page of a user is duplicated. Thus, I declare the input as follows:
<input type="email" name="email" required
placeholder="Dirección de correo"
data-parsley-trim-value="true"
data-parsley-trigger="change"
data-parsley-remote-options='{ "type": "POST", "dataType": "jsonp" }'
data-parsley-remote="checkmail.php"
data-parsley-remote-message="Mail duplicated"
class="form-control">
The checkmail.php code is:
require_once("../functions/mysqli_connect.php");
if (empty($_POST['email'])){
$errors[] = 'No llega el parametro de mail';
}else {
$email = trim($_POST['email']);
$q = ("select * from register where email ='" . $email . "'");
$r = mysqli_query($dbc, $q);
if ($r) {
if (($r->num_rows) > 0) {
echo json_encode(404);
} else {
echo json_encode(200);
}
}
}
I've tried multiple combinations for echo response, I've read all the messages on stackoverflow but couldn't find the solution because I've always get the message :
This value seems to be invalid.
As I read on another's user question I've tried:
data-parsley-remote-message="Mail duplicated"
but with no luck either.
The PHP code works as expected, so no errors there, but Parsley always treats the json_encode responses as it is was an error.
Any help would be vey appreciated.
Thanks in advance.
Parsley remote validator looks for HTTP response code not for the body content itself. In your example you're returning json data with probably always HTTP 200 status code.
Maybe look here http://php.net/manual/en/function.http-response-code.php or here Set Response Status Code to see how you could change the response status code.
Best
I have a problem with an input field in a view called add.ctp. When the input type is set to 'text', the program sequence is normal. But when I change the input type to 'hidden', the following error is displayed:
The request has ben black-holed. Error: The requested address was not found on this server.
mod-rewrite seems activated. Any ideas, what can be the reason for this?
There is no error with your code. CakePHP's Security component checks hidden form fields to prevent tampering by end users:
By default SecurityComponent prevents users from tampering with forms. It does this by working with FormHelper and tracking which files are in a form. It also keeps track of the values of hidden input elements. All of this data is combined and turned into a hash. When a form is submitted, SecurityComponent will use the POST data to build the same structure and compare the hash.
Use FormHelper::unlockField to make a field exempt from this feature:
$this->Form->unlockField('User.id');
This means there is an error with your code. Here is how to create hidden textbox
echo $this->Form->input('field_name', array('type'=>'hidden'));
I think It's because you are using SecurityComponent.
THe component monitor the form integrity, the hidden field shouldn't change from the user and because of that the security component "decide" that the something malicious has been done with the form for example CSRF attack and it prevent the submit. And I believe you are having some JavaScript which change the field value for some reason.
CakePHP 3
Please do not unlock fields/disable CSRF security component for any
particular action. This is important for the form security.
for those who are getting "The request has been black-holed."
,"form tampered error", "you are not authorized to access
that location." or "unexpected field in POST data". It is
mainly due to the CSRF component working as expected.
Disabling or modifying it is not a solution. Instead of disabling, please follow the right approach.
The right way should be as below:
On the Form, Add a hidden field as below.
<?= $this->Form->text('TPCalls.ID',['label' => false, 'class' => 'hidden']); ?>
before AJAX add the field
$("input[name='TPCalls[ID]']").val(event.id);
Then serialise it
var el = $("#xyzForm");
var ajaxTPCalls = el.serializeArray();
$.ajax({
type: el.attr('method'),
async: true,
url: el.attr('action'),
data: ajaxTPCalls,
dataType: "json",
cache: false,
success: function (data) {
toastr.success(data.message, data.title);
},
error: function (jqXHR) {
if (jqXHR.status == 403) {
$("body").html(jqXHR.responseText);
}
}
});
This way you do not disable CSRF or unlock any field. Any suggestions welcome.
I am having trouble with trying to get backbone to send a PUT request out to my rails server on save. I am not sure what I am doing wrong here, it is fine with GET requests just not PUT..
Here is the code that is in my view that I use to save my model.
e.preventDefault()
$(#el).find('#error_explanation').html ""
data = Backbone.Syphon.serialize(this)
setError = false
#model.set(data, error: (model, error) ->
setError = true
)
#model.save()
Any help would be greatly appreciated.
Thanks,
-do
Stupid me....
Here is what was in my model.
validate: ->
console.log "validating"
console.log "options: #{options}"
errors = []
if(!#.validateEmail(#.get('email')))
errors.push("Email can't be blank")
if(!#.validateName(#.get('first_name')))
errors.push("First name can't be blank")
if(!#.validateName(#.get('last_name')))
errors.push("Last name can't be blank")
return errors
This was actually being called when I was trying to save it which I was just trying to call manually. Since I wasn't returning the correct data saying that it was valid/invalid it just was always invalid.
ooops...
-do
I am a 3+ years old in cakephp and facing a somewhat strange issue
with submitting a form to plugin controller's action (i am using
plugin first time). After trying different known things i am posting
this one.
Going straight into the matter here is the form in my "forum" plugin's search_controller.php's "index" view:
echo $form->create("Search", array('url'=>array('controller' =>
'search', 'action' => 'index','plugin'=>'forum'),
'id'=>'searchFormMain'));
<input type="text" name="data[Search][keyword]" style="width:357px; margin-left:9px;"><p><span id="searchButton"><input
type="image" src="/img/button_search.jpg" style="height:40px;width:
136px;border:0;" class="handcursor"></span></p>
</form>
As i am submitting this form to "index" action of search controller of
forum plugin, the following code does print nothing:
public function index($type='') {
if(!empty($this->data)) {
pr($this->data);
die;
}
}
While if i try the same code within beforeFilter of the same
controller i.e. search_controller.php it works well and prints as
follows:
Array
(
[Search] => Array
(
[keyword] => Hello Forum
)
)
And finally here is the beforeFilter code (of search_controller.php):
public function beforeFilter() {
parent::beforeFilter();
if(!empty($this->data)) {
pr($this->data);
}
}
Fyi, it does not matter if i comment out "parent::beforeFilter();" or
even disable $uses of my controller (if they look doubtful to you)
the result is same i.e. the control is not going in to "index" action
in the case of form submit while is working fine in the case of page
call. The url/action to page is http://localhost.rfdf.org/forum/search/index.
If i call the url directly it loads the form fine but when i submit it, it
never gets into the "index" action of the controller thus no view
rendered.
If i try the same set of code out of "forum" plugin environment i.e. in normal application it works just fine
I have been trying to find a way out of this for last 3+ hours now but
no success. I would appreciate any help in solving this puzzle.
I got it, finally!
It was Securty compontent dropping the request into the blackHole whenever it failed to find a security token with the form data. I learned that "Security" component "interferes" with $form->create() method and places a token as a hidden field with each $form->create() call. On the form submit, just after beforeFilter and right before getting into the controller "action" it checks for this token and simply dies everything on a validation failure. Unfortunately there is no error message or entry to cake log.
In my case i had been creating my own custom tag and not with the help of $form->create method so no token was being generated which lead to all the pain.
I resolved it by placing
$this->Security->validatePost = false;
at the end of beforeFilter.
Thanks everyone!
Have you tried putting an else into that if(!empty($this->data)) and doing a pr() as it could be that your post is not empty.
Either that or the format of your url array is not correct.
From ln759, http://api.cakephp.org/view_source/router/#line-757
$defaults = $params = array('plugin' => null, 'controller' => null, 'action' => 'index');
So I guess you need plugin first?
Are you using ACL or any of the like? In the beforeFilter, do a pr of the request. See which action is being requested to make sure that the request is correct