Laravel: Can't set object values - php

I have a form in Laravel that when it submits, the function donorUpdate is going to be called, and it will save the data to the database. Here is the exact code of the function.
My aim is, the form contains the field name DonorPrefix that when it's empty, the default value should be Mx.. I have tried the code below, and it doesn't work.
public function donorUpdate(Request $request, Donor $donor){
if($request->has('DonorPrefix') == false || $request->DonorPrefix == '' || $request->DonorPrefix == null){
$request->DonorPrefix = 'Mx.';
}
$donor->update($request->all());
return redirect('/donor/'.$donor->DonorID);
}
This is where the weird part start: My debugging attempt is that I commented the return redirect('/donor/'.$donor->DonorID); line and replace with return $request->all(), the value for DonorPrefix is "" (Empty string).
However when I tried return $request->DonorPrefix, the prefix Mx. returned.
Why isn't the value of DonorPrefix is Mx. on $request->all(), but is Mx. on return $request->DonorPrefix?
Edit: I'm certain that other parts of code works like charm. Things are smooth untill I tried adding this 'default value' function.

You can't set request parameters like $request->DonorPrefix = '...'.
To set a parameter on the request you need to use offsetSet like this:
$request->offsetSet('DonorPrefix', 'Mx.');
Also, the has() method already ensures that it is a non-empty string so you can remove some of your checks, and simplify your code like this:
if(!$request->has('DonorPrefix')){
$request->offsetSet('DonorPrefix', 'Mx.');
}

Related

Arguments not working propelry in codeigniter 3

I am trying to pass a string named "publicUsers" in a callback function, but when I display the argument in my console I see the following string... &Z34Sf{;Cr(m
I have included a trait named "VerifyLogin" in my controller which has a function named VerifyAndSetSession
Any help would be really appreciated
below is my code
if(isset($_POST['sign_in']))
{
$this->emailPassValidation("","|callback_VerifyAndSetSession[publicUsers]");
}
This is emailPassValidation method""
function emailPassValidation($new_account_call_back,$sign_in_callback ){
$this->form_validation->set_rules("password","password","required{$sign_in_callback}",
['required' => 'Please enter your %s']);
}
This is where I am debugging the passed arg
trait VeirfyLogIn
{
function VerifyAndSetSession($infoType)
{
fb($infoType, "Infotype");
//This shows in the console.log &Z34Sf{;Cr(m ???
exit;
}
}
Form validation callbacks accept by default one parameter which is the value of the input to check.
It means that :
$this->form_validation->set_rules("field","field","callback_checkField");
Will imply a callback function like this :
public function checkField($field_value){}
If you want to pass extra data to your callback, you can set that value like you did with brackets :
$this->form_validation->set_rules("field","field","callback_checkField['othervalue']");
That new var will not replace the default parameter but add a new one :
public function checkField($field_value, $othervalue){}
So in your case, for :
callback_VerifyAndSetSession[publicUsers]
the function should be :
function VerifyAndSetSession($fieldvalue, $infoType)

Laravel - both input values can't be no how to validate?

I'm using Laravel for a project and want to know how to validate a particular scenario I'm facing. I would like to do this with the native features of Laravel if this is possible?
I have a form which has two questions (as dropdowns), for which both the answer can either be yes or no, however it should throw a validation error if both of the dropdowns equal to no, but they can both be yes.
I've check the laravel documentation, but was unsure what rule to apply here, if there is one at all that can be used? Would I need to write my own rule in this case?
very simple:
let's say both the fields names are foo and bar respectively.
then:
// Validate for those fields like $rules = ['foo'=>'required', 'bar'=>'required'] etc
// if validation passes, add this (i.e. inside if($validator->passes()))
if($_POST['foo'] == 'no' && $_POST['bar'] == 'no')
{
$messages = new Illuminate\Support\MessageBag;
$messages->add('customError', 'both fields can not be no');
return Redirect::route('route.name')->withErrors($validator);
}
the error messge will appear while retrieving.
if you get confuse, just dump the $error var and check how to retrieve it. even if validation passes but it gets failed in the above code, it won't be any difference than what would have happened if indeed validation failed.
Obviously don't know what your form fields are called, but this should work.
This is using the sometimes() method to add a conditional query, where the field value should not be no if the corresponding field equals no.
$data = array(
'field1' => 'no',
'field2' => 'no'
);
$validator = Validator::make($data, array());
$validator->sometimes('field1', 'not_in:no', function($input) {
return $input->field2 == 'no';
});
$validator->sometimes('field2', 'not_in:no', function($input) {
return $input->field1 == 'no';
});
if ($validator->fails()) {
// will fail in this instance
// changing one of the values in the $data array to yes (or anything else, obvs) will result in a pass
}
Just to note, this will only work in Laravel 4.2+

Propel validation error with different objects

we're using a custom email validator and we're having a problem validating two different objects which have a relation to the same object.
Here is the example code:
$ti = EnumTipoInteresadoQuery::create()->findOne();
$i1 = new Interesado();
$i1->setTipoInteresado($ti);
$i1->setMail('testexample.com');
var_dump($i1->validate()); // Must be false and we get false. OK!
$i2 = new Interesado();
$i2->setTipoInteresado($ti);
$i2->setMail('hello#example.com');
var_dump($i2->validate()); // Must be true but we get false. BAD!
When we validate the first one ($i1) everything goes ok. When we validate the second one ($i2) we get false when we should get true!
Inside the custom validator we echoed a message with the string that gets validated:
class EmailValidator implements BasicValidator
{
public function isValid(ValidatorMap $map, $str)
{
echo "Validating $str\n";
return preg_match('/^([^#\s]+)#((?:[-a-z0-9]+\.)+[a-z]{2,})$/i', $str) !== 0;
}
}
Looking at the output we see the following:
Validating testexample.com
bool(false)
Validating testexample.com
Validating hello#example.com
bool(false)
We can clearly see that the second validation ($i2) calls the custom validator twice, first with the mail of the first object ($i1) and then with the mail of the second ($i2).
We suspect that, as the two objects have a reference to a common object ($ti) the validation somehow "cascades" and validates the first ($i1) and second ($i2) object.
Is there any workaround for this issue? Is it a bug? Is it something we're doing wrong?
Thanks in advance!
Andrés

Codeigniter issue with submitted variables as blank

I have a form :
<?php
$attr = array('id'=>'urlSubmit');
$urlInputAttr = array('name'=>'urlInput','value'=>'yourdomain.com','maxlength'=>'50','size'=>'25');
echo form_open('urlSubmission',$attr);
echo form_input($urlInputAttr);
#echo form_submit('urlInput', '');
echo form_close();
?>
a controller called urlsubmission
$this->load->model('domaincheckmodel');
$this->domaincheckmodel->verifyduplicates($this->input->post('urlInput'));
and a function within a model(domaincheckmodel) which basically checks for duplicate records and inserts a new domain:
function verifyduplicates($tldEntered){
# $_POSTed value of urlInput
## Gather if the domain exists in db
$DupDomains = $this->db->get_where('ClientDomain', array('tld'=>$tldEntered));
if($DupDomains->num_rows() > 0 ){
$this->load->view('err/domainexists'); ##domain already used
}
# else, no domain present, insert.
else{
#array of insert values:
$insertNewDomain = array('tld'=>$this->input->post('urlInput',TRUE));
$this->db->insert('ClientDomain', $insertNewDomain);
$this->load->view('success/domainfree'); ##domain is free and has been entered.
}
}
$this->domaincheckmodel->verifyduplicates($this->input->post('urlInput'));
function verifyduplicates($tldEntered){
# $_POSTed value of urlInput
## Gather if the domain exists in db
$DupDomains = $this->db->get_where('ClientDomain', array('tld'=>$tldEntered));
You're passing from the form to the controller to the model, are you sure the post variable is staying populated? Try the above, capture the post variable in the controller and pass it to the model instead of trying to read it in the model itself?
A little clarification on passing parameters to functions. You can do this via whatever is inside the brackets as follows.
Controller:
$myVariable = $this->someModel->someFunction($someParameter)
Model:
function someFunction($variableIWantToPopulateWithSomeParameter)
So someParameter gets passed from the controller to the function name in the model. There is one thing to be aware of though and that is that model function now EXPECTS a parameter and if you don't give it one, ie you call someFunction() you'll get an error. This can be avoided by giving it a default value like this:
function someFunction($myVariable = 1)
What that is going to do is say if I don't get a value passed to me I am going to make $myVariable equal to one, if I do I'll overwrite 1 with the new value. So if you send two calls to that function this is what you can expect:
//$myVariable is going to be 1, the default.
$this->someModel->someFunction();
//$myVariable is going to be 5, the value passed to it
$this->someModel->someFunction(5);

Zend_Form set and validate field value manually

I have a Zend_Form with a dropdown field.
When the user sets a value in the url this one should be selected as default value in this dropdown.
So what i do at the moment is this:
$parlang = $this->getRequest()->getParam('lang');
if($parlang){
$this->view->filterForm->getElement('ddLanguage')->setValue($parlang);
}
if ($this->getRequest()->isPost()) {
if($this->view->filterForm->isValid($_POST)){
...
...
...
No i want to check if the value of the variable is even a valid value for the dropdown? How can i check this in coorporation with the form validation. Yes i can check the variable against a array or so but this seems to be "fighting against the framework".
So what is the Zend way to do such a thing?
Edit:
My final solution for all who are interested, is:
$parlang = $this->getRequest()->getParam('lang');
if($parlang){
$ddLanguage = $this->view->filterForm->ddLanguage;
if($ddLanguage->isValid($parlang)){
$ddLanguage->setValue($parlang);
$language = $parlang;
}
}
I ran a quick test and it looks like one method you can use is Zend_Form_Element_Select::getMultiOption() to check if the language exists in the select values.
<?php
$parlang = $this->getRequest()->getParam('lang');
if ($parlang) {
$el = $this->view->filterForm->getElement('ddLanguage');
// attempt to get the option
// Returns null if no such option exists, otherwise returns a
// string with the display value for the option
if ($el->getMultiOption($parlang) !== null) {
$el->setValue($parlang);
}
}
If your Multiselect element contains a list of country, I would just populate a default in your element value according to the one in the URL.
In order to do so, you could create a custom Zend_Form_Element as follow:
class My_Form_Element_SelectCountry extends Zend_Form_Element_Select
{
protected $_translatorDisabled = true;
public function init()
{
$locale = Zend_Registry::get('Zend_Locale');
if (!$locale) {
throw new Exception('No locale set in registry');
}
$countries = Zend_Locale::getTranslationList('territory', $locale, 2);
unset($countries['ZZ']);
// fetch lang parameter and set US if there is no param
$request = Zend_Controller_Front::getInstance()->getRequest();
$lang = $request->getParam('lang', 'US');
// sort your country list
$oldLocale = setlocale(LC_COLLATE, '0');
setlocale(LC_COLLATE, 'en_US');
asort($countries, SORT_LOCALE_STRING);
setlocale(LC_COLLATE, $oldLocale);
// check weither the lang parameter is valid or not and add it to the list
if (isset($countries[$lang])) {
$paramLang = array($lang => $countries[$lang]);
$countries = array_merge($paramLang, $countries);
}
$this->setMultiOptions($countries);
}
}
You get the idea from this custom form.
If what you're trying to do isn't a Multiselect field filled by a country list but a list of language instead, then the logic is the same, you just need to change the call to the static method Zend_Locale::getTranslationList()and grab whatever information you need.
One more thing, if you just want a single element in your Multiselect element, then go for a Zend_Form_Element_Hidden.
It's a lot of "if" but I can't understand how looks like your Multiselect element exactly from your question.
Now let's take a look on the validation side, when you're using a Multiselect element, Zend_Framework automatically adds an InArray validator, which means that you don't have anything to do to check weither the data sent are correct or not. isValid is going to do it for you.
Weither a user let the default parameter and everything will be fine, or he modifies/deletes this parameter and the default parameter (en_US in this case, see code above) is going to be set as a default value for the Multiselect field.
To answer your last question, no it's not against the framework to check a variable set by a user and compare it with an array (from getTranslationList()for example). I would say it's even the recommended way to do things.

Categories