Codeigniter issue with submitted variables as blank - php

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);

Related

I can not access a POST within my class in PHP

I have an HTML form with method = "POST" and a submit button. Within my file 'purchases.controller.php', if I do a var_dump ($_POST), you can see all my POST variables belonging to the inputs of the form correctly.
Now, I have another file called 'aux.php' which gets an array by AJAX and then I pass it to a function of a class in the file 'purchases.controller.php'. There, I want to manipulate the array and the POST variables that are arriving, but it only allows me to manipulate the array, the POST within the function do not exist.
Does anyone know what I'm doing wrong?
I share the purchases.controller.php code:
//HERE SHOWS ME THE POST VARIABLES AS THE 'registroUsuario', ETC.
var_dump($_POST)
class Purchases {
public function ctrCash(&$completeArray){
//THE ARRAY IS SHOWN CORRECTLY
var_dump($completeArray);
if(isset($_POST["registroUsuario"])){
if(preg_match('/^[a-zA-ZñÑáéíóúÁÉÍÓÚ ]+$/', $_POST["registroUsuario"]) &&
preg_match('/^([0-2][0-9]|3[0-1])(\/|-)(0[1-9]|1[0-2])\2(\d{4})$/', $_POST["registroCalendario"]) &&
preg_match('/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/', $_POST["registroEmail"]) &&
preg_match('/^(?:\D*\d){2,4}\D*$/', $_POST["registroDireccion"]) &&
preg_match('/^[0-9]{7,12}$/', $_POST["registroTelefono"])) {
//HERE I WANT TO MANIPULATE EVERYTHING, BUT I CAN NOT SINCE THEY ARE NOT ARRIVING THE POST
}
And here is the file aux.php:
if(isset($_POST['completeArray'])){
include ('purchases.controller.php');
$completeArray = json_decode($_POST['completeArray'], true);
$newPurchase = new Purchase();
$newPurchase -> ctrCash($completeArray);
}

Laravel: Can't set object values

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.');
}

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)

Zend View array variable inside a partialLoop

Here is the code in my controller:
$this->view->myArray = array();
$this->view->test = "";
$out = $this->view->partialLoop('tab/partial.phtml', $data);
echo $this->view->test; // Output: This works
echo count($this->view->myArray); // Output: 0
And the partial partial.phtml:
$v->test = $this->partialLoop()->view;
$v = "This works";
echo $v->test; // Output: This works
$v->myArray[] = "hello";
echo count($v->myArray); // Output: 0
I don't think that accessing view variables from a partialLoop is a wonderful idea. That aside, why doesn't it work for my array variable?
it doesn't work because you don't have access to the view variables in the partial. You have access to the data you pass to the partial.
$out = $this->view->partialLoop('tab/partial.phtml', $data);
This line of code would have access to the information contained in $data.
So this code in your current partial is basically meaningless:
$v = $this->partialLoop()->view; //you choose to assign view data to the partial, and I don't think it's working as expected.
//By not passing any args to the partial you have at least some access to the view object.
$this->view->test = "This works";//assign data to view locally
echo $v->test; // you seem to be echoing out locally assigned data
$v->myArray[] = "hello";//you didn't assign this to the view
echo count($v->myArray); // myArray probably doesn't exist in this context or dosen't work as expected. If you make this an associative array it might work.
I don't think I've ever seen partials used in quite this manner before. The point of the partial is to establish a different variable scope for a specific portion of the view.
The partial and partialLoop are view helpers so the only action you need to take in your controller (data may be or come from a model as well) is to make available any data you want to use in your partials as well as any data you want available in your normal view scope.
//in a controller
public function userAction() {
$model = Application_Model_DbTable_User();//Table columns = id, name, role
$this->view->partailData = $model->fetchAll();//assign data to view that we want to use in partial, should be an array or object.
}
//in a view script
<?php
//pass the path to the partial as the first arg and the data to be displayed as the second arg
echo $this->partialLoop('/path/to/partial.phtml', $this->partialData);
//we could pass data explicitly as well
echo $this->partial('/path/to/partial.phtml', array('id'=>1,'name'=>'jason','role'=>'user'));
?>
//now for our partial.phtml
//this could be used a simple partial or as a partialLoop
<p>My name is <?php echo $this->name ?>.</p>
<p>My data file id is <?php echo $this->id ?>.</p>
<p>My access control role is <?php echo $this->role ?>. </p>
<!-- name, id and role would be column names that we retrieved from the database and assigned to the view -->
To use a partial or partialLoop you need to pass an array of some type or an object that implements toArray().
[EDIT]
Clean up your code your still in left field.
//controller code
$this->view->myArray = array();
//view code
<?php $v = $this->partial()->view ?>
<?php $v->myArray[] = 'newName' ?>
<?php Zend_Debug::dump(count($this->partial()->view->myArray)) ?>
//my output =
int(1)
I don't seem to be able to pass the view any further then this, if I assign to an actual partial script and attempt to output the view object errors are thrown:
//my view again
<?php echo $this->partial('partial.phtml', $this->partial()->view) ?>
//This and attempts similar result in the error
/*Catchable fatal error: Object of class Zend_View could not be converted to string in E:\www\home-local\application\views\scripts\partial.phtml on line 1*/
//when the partial.phtml looks like
<?php echo $this />
//however when I access the data available in the view
<?php echo $this->myArray[0] ?>
//the result works and the output is
newName
it looks like an empty partial() (partialLoop()) call will give you access to the view object, when you already have access to the view object. If you leave the scope of the view object you will have only the access available to your current scope as provided by __get() and __call().
I hope I was able to explain this enough to help.
maybe you cant set the value of $v or the item because its private or static or discarded
also from the code you posted its using recursion which could make it a lot more breakable (ie the controller is referencing the views data, and the view is setting it or hasnt set it or has set it twice)
agreed i dont think accessing view var's from a partialLoop is a good idea.
edit:
$this->view->assign('variablename', $my_array);
I think the variable is otherwise "lost" on the Rerender, so work on your variables in your controller, and before you are done assign them to the view. I wouldn't really do array operations on $this->view->myArray

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