Getting Custom Error Message Array in Codeigniter - php

Just trying to find out the best way to get my custom error message working. Isset does not seem to work in codeigniter.
And for some reason my inputs are displaying the number '1'
Controller
<?php
class Step_3 extends MX_Controller {
private $error = array();
public function index() {
if(($this->input->server('REQUEST_METHOD') == 'POST') && $this->validate()) {
$data['db_hostname'] = $this->input->post('db_hostname');
}
if ($this->error['db_hostname']) {
$data['error_db_hostname'] = $this->error['db_hostname'];
} else {
$data['error_db_hostname'] = '';
}
if ($this->input->post('db_hostname')) {
$data['db_hostname'] = $this->input->post('db_hostname');
} else {
$data['db_hostname'] = 'localhost';
}
}
private function validate() {
if (!$this->input->post('db_hostname')) {
$this->error['db_hostname'] = 'Hostname required!';
}
}
} // End Of
On View File Sample
<input type="text" name="db_hostname" value="<?php echo $db_hostname; ?>" id="input-db-hostname" class="form-control" size="50"/>
<?php if ($error_db_hostname) { ?>
<div class="text-danger"><?php echo $error_db_hostname; ?></div>
<?php } ?>

Your "validate" function doesn't return anything, so your first if statement will never be true.
Also at the moment the input will automatically have a value of 'localhost'. It may be better to test for an empty string and strip spaces just in case like this:
if ("" == trim($this->input->post('db_hostname')))

Related

How to get submitted variable into a function

I am very sorry if this is very obvious, but I am banging my head against the wall on how to solve this
I have a form and I would like to use the submitted form value in to a function
the form:
form.php
<form action="my.php" method="post" enctype="multipart/form-data">
<input id="my-item-calc" name="my-item-calc" value="29.00">
<td>
<input type="submit">
</form>
my.php
class Jcart{
private $calcdel =0;
public function get_contents() {
return $items;
return $calc['calcdel'];
}
private function add_calc($calcdel){
$validCalcdel = false;
//Verify if the calculate value is numberic
if (is_numeric($calcdel)) {
$validCalcdel = true;
}
if ($validCaldel !== false) {
$this->calcdel = $calcdel;
}
}
public function display_cart() {
$config = $this->config;
$errorMessage = null;
// Simplify some config variables
$checkout = $config['checkoutPath'];
$priceFormat = $config['priceFormat'];
$calcdel = $config['calc']['calcdel'];
// Use config values as literal indices for incoming POST values
// Values are the HTML name attributes set in config.json
$calcdel= $_POST[$calcdel];
if ( isset($_POST[$calcdel]) ) {
$calcdel = $_POST[$calcdel];
$calcAdded = $this->add_calc($calcdel);
if ($calcAdded = true){
$this->calcdel = $calcdel;
}
}
}
}
When I submit the form it will echo 29.00 for the $calcdel how ever this $this->calcdel output is empty
Any help how I would be able to pass the value into $this->calcdel and echo it out
Hope this will work
class Jcart{
private $calcdel =0;
public function get_contents() {
return $items;
return $calc['calcdel'];
}
private function add_calc($calcdel){
$validCalcdel = false;
//Verify if the calculate value is numberic
if (is_numeric($calcdel)){
$validCalcdel = true;}
if ($validCaldel !== false){
$this->calcdel = $calcdel;
}
}
public function display_cart() {
$config = $this->config;
$errorMessage = null;
// Simplify some config variables
$checkout = $config['checkoutPath'];
$priceFormat = $config['priceFormat'];
$calcdel = $config['calc']['calcdel'];
// Use config values as literal indices for incoming POST values
// Values are the HTML name attributes set in config.json
$calcdel= $_POST[$calcdel];
$calcAdded = $this->add_calc($calcdel);
if ($calcAdded){
$this->calcdel = $calcdel;
}
}}
$jcart = new Jcart();
if (isset($_POST[$calcdel]))
{
$jcart->display_cart();
}

Learning OOP in PHP. Is this the correct way to do this?

I've just started learning to do oop and I just wanted to put the most basic set of code together to make sure I'm understanding things correctly. I wanted to capture a form entry in the $_POST variable and pass it to an object to have it output something back to the browser. No SQL, no Security measures, just proof of understanding.
Here is the form:
<html>
<head>
<title>SignUp Form</title>
</head>
<body>
<?php
if(!empty($_POST['name'])) {
include_once "class.php";
} else {
?>
<form method="post" action="signup.php">
<label for="name">Enter name below:</label></br>
<input type="text" name="name" id="name"></br>
<input type="submit" value="Submit">
</form>
<?php
}
echo $name->processName($_POST['name']); ?>
</body>
</html>
And here is the class:
<?php
class Process {
public $entry;
function __construct($entry) {
$this->entry = $entry;
}
public function processName($entry) {
return "You entered " . $this->entry . ".";
}
}
$name = new Process($_POST['name']); ?>
This is working without error right now but it doesn't seem like I should have to enter the $_POST in the echo statement on the form page and in the object on the class page. Is this correct? Should I instead be collecting that in the $entry property. It's working, but I don't think the execution is correct. Thanks in advance!
Your right you don't need to enter the $_POST variable into that function, you could change it to this and it would work without entering the post:
public function processName() {
return "You entered " . $this->entry . ".";
}
Because right now processName function doesn't do anything with the class's public $entry variable, it just echoes out what you put in when you call the function.
What you likely want to do instead is:
Change public $entry; to protected $entry;
Then:
public function getEntry() {
return $this->entry;
}
Then in your html, after constructing the class, you can just put this to get the $entry variable:
echo $name->getEntry();
Coming from Symfony framework background. You could do something right this:
<?php
class Process
{
protected $post_var;
public function __construct($p)
{
$this->post_var = $p;
}
public function getData()
{
//checking if not post request
if(count($this->post_var) == 0) {
return false;
}
$result_arr = [];
//populating $result_arr with $_POST variables
foreach ($this->post_var as $key => $value) {
$result_arr[$key] = $value;
}
return $result_arr;
}
}
$process = new Process($_POST);
$data = $process->getdata();
if($data)
{
echo $data["name"];
}
?>
<form action="" method="post">
<input type="text" name="name"/>
<input type="submit" name="submit"/>
</form>

Sending a variable to the view which is used in controller with phalconPHP

I have a small issue i have declared a variable of type Boolean in my controller.
$done=False
Now there is a trigger in the controller that would turn it to True and it is at this point i would like to send it to the corresponding view with this controller .. i have used the following.
$done=True;
$this->view->setVar("done", $done);
Now when i try to call it in the corresponding view it does not know anything of this varible.
if($done==True)
{
echo'
<div class="alert alert-success">
Add Another Here!
</div>
';
}
It gives me the following:
Notice: Undefined variable: done in >C:\xampp\htdocs\Blueware\app\views\addNewSkill\index.phtml on line 36
Now is there a better way of sending this varible through to the view or am i making a mistake?
Full Controller/Action Code:
<?php
class addNewSkillController extends \Phalcon\Mvc\Controller{
public function indexAction(){
}
public function confirmAction(){
$this->view->disable();
$done=False;
if($this->request->isPost()) {
$dataSent = $this->request->getPost();
$skill = new Skills();
$skill->technology = $dataSent["technology"];
$skill->skillName = $dataSent["skillName"];
$skill->description = $dataSent["description"];
$savedSuccessfully = $skill->save();
if($savedSuccessfully) {
$done=True;
$this->view->setVar("done", $done);
} else {
$messages = $skill->getMessages();
echo "Sorry, the following problems were generated: ";
foreach ($messages as $message) {
echo "$message <br/>";
}
}
} else {
echo "The request method should be POST!";
}
}
}
Full View Code:
<?php
if($done==True)
{
echo'
<div class="alert alert-success">
Add Another Here!
</div>
';
}
?>
if($savedSuccessfully) {
$done=True;
$this->view->setVar("done", $done);
} else {
You should be setting the variable there, But setting in the view after seems that its not saving and therefore not passing the variable on
similar to
if($savedSuccessfully) {
$done=True;
} else {
...later in code ...
$this->view->setVar("done", $done);
or even just
$this->view->setVar("done", $savedSuccessfully);

populate dropdown in codeigniter

I have difficulty with populating dropdown
This is the add.php view
<?php
echo form_open('',$attributes);?>
<table cellpadding="0" cellspacing="0" class="user_table biz_table">
<tr>
<th>City:</th>
<td>
<select id="city_id" name="city_id">
<?php foreach($cities as $c){ ?>
<option value="<?php echo $c->id; ?>" <?php if ($biz['city_id']===$c->id){
>selected="selected"<?php }?> ><?php echo $c->name?></option>
<?php }?>
</select>
<tr>
<th>Neighborhood:</th>
<td>
<select id="district_id" name="district_id">
<option value=""></option>
<?php foreach($districts as $d){ ?>
<option value="<?php echo $d->id; ?>" <?php if($biz['district_id']===$d->id){?
>selected<?php }?>><?php echo $d->name?></option>
<?php }?>
</select>
<span style="color: red;"><?php echo form_error('district_id'); ?></span>
</td>
</tr>
This is the javasript. I believe it was used to refresh the page!!!!!
<script type="text/javascript">
var cities = [];
<?php foreach($cities as $city):?>
cities[<?php echo $city->id ?>] = '<?php echo $city->name?>';
<?php endforeach;?>
$(function(){
$('#city_id').change(function(){
city_id=$('#city_id').val();
Utils.loadAction('#district_id','/biz/get_children/'+city_id+'/city');
});
$('#catid_1').change(function(){
catid_1=parseInt($('#catid_1').val());
Utils.loadAction('#subcat','/biz/get_children/'+catid_1+'/category');
});
<?php if(isset($biz['rating']) && $biz['rating']>0):?>
var biz_rating=parseInt('<?php $biz['rating']?>');
if(biz_rating>0)
{
$('#rating').val(biz_rating);
$('.star-'+biz_rating).addClass('active-star');
$(".rating-hint").html($(".star-"+biz_rating).attr("title"));
}
<?php endif;?>
});
This is a controller biz.php
Class Biz extends CI_controller
{
function __construct()
{
parent::__construct();
}
public function add()
{
if(!$this->tank_auth->is_logged_in())
{
redirect('/ucp/login/');
}
$this->load->helper('form');
$biz=$this->get_form_data();
$with_review=1;
if(!empty($_POST)&&!isset($_POST['with_review']))
{
$with_review=0;
}
//validating
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('','');
$this->form_validation->set_rules('city_id', 'City',
'trim|required|intval|max_length[20]|callback_city_check');
$this->form_validation->set_rules('district_id', 'District',
'trim|intval|max_length[20]|callback_city_check');
if($this->form_validation->run())
{
//get validated data
$biz=$this->get_form_data();
}
//save business
$this->load->model('bizs');
$bizid = $this->bizs->add($biz);
redirect('/biz/'.$bizid);
}
//get cities
$this->load->model('catsAndCities','cc');
$this->cc->set_table_name('city');
$data['cities'] = $this->cc->get_top();
if(!$biz['city_id'])
{
//$city=$data['cities'][0];
$biz['city_id'] = 0;
if($this->tank_auth->get_user_city())
$biz['city_id']=$this->tank_auth->get_user_city()->id;
}
$data['districts']=$this->cc->get_children($biz['city_id']);
//$data['districts']=$this->cc->get_children($biz['city_id']);
//$data['districts']=$this->cc->get_children();
$data['biz']=$biz;
$data['heading']="Add A Business";
$this->load->view('biz/add',$data);
}
get_form_data() inside controller biz.php
private function get_form_data()
{
$biz=array(
'city_id'=>$this->input->post("city_id"),
'district_id'=>$this->input->post("district_id")
);
return $biz;
}
get User city in libraries/tank_auth.php
function get_user_city()
{
$this->ci->load->model('catsAndCities','cc');
$this->ci->cc->set_table_name('city');
$this->ci->load->helper('cookie');
if($cookie_v = get_cookie($this->ci->config-
>item('default_city_cookie_name'),TRUE))
{
if($city = $this->ci->cc->get($cookie_v,'slug'))
{
if($city->parent_id == 0)
{
$this->city = $city;
return $city;
}
}
}
$city = array_shift($this->ci->cc->get_top());
$this->city = $city;
return $city;
}
These two are in model catsandcities.php
public function get_all()
{
$data=array();
$this->db->order_by('parent_id','asc');
$this->db->order_by('`order`','asc');
$query=$this->db->get($this->table_name);
foreach($query->result() as $row)
{
$data[$row->id]=$row;
}
return $data;
}
public function get_children($parent_id)
{
$children=array();
if($items=$this->get_all())
{
foreach($items as $i)
{
if($i->parent_id === $parent_id)
{
$children[]=$i;
}
}
}
return $children;
}
the files are located here https://github.com/leungxd/upble
Thanks
I don't fully understand your question but looking at the code I see a lot of hassle to do a simple task. My advice:
Use the form helper to generate the dropdowns
Simplify the way you access your data and delegate the controller to only retrieve such data
Put as little as you can in the views, don't do any logic there
1 - use the form helper
<?= form_dropdown('city_id', $cities, 'default') ?>
This will generate the select and options html code for you. Just make sure it is inside the form_open() function.
2 - Simplify the way to access data...
Take for example your method:
public function get_children($parent_id)
{
$children=array();
if($items=$this->get_all())
{
foreach($items as $i)
{
if($i->parent_id === $parent_id)
{
$children[]=$i;
}
}
}
return $children;
}
Instead of loading all the records from your table, filter by the parent on a query level:
public function get_children($parent_id)
{
$this->db->where('id_parent', $parent_id);
$query = $this->db->get($this->table_name);
$result = $query->result();
return $result;
}
3 - Don't put logic on the views
I would suggest to create a method in your controller where you return a json encoded object and then call it by an ajax request with jquery and then populate the children dropdown:
public function get_children($parent_id)
{
$this->db->where('id_parent', $parent_id);
$query = $this->db->get($this->table_name);
$result = $query->result();
if(empty($result) == FALSE) {
return json_encode($result);
}
return NULL;
}
So whenever you call yoururl/controller/get_children and pass the parent id by a post you'll get the children for that city in a json encoded way that you can get with jquery to manipulate data client-side, instead of having thousands of records bloating up your html.
Read the guidelines of stackoverflow or you won't get much help, and try to be clear on what problem you are trying to solve. Good luck!
I just added a subdomain, and it solved the problem.
thanks

the best approach to giving an error message when validating

I am a new programmer and am attempting to do some validation for a basic registration form. I have built a basic registration form that sends the user back to the same page when submitted. I have also created a user class and have created some basic validation functions. However, the functions have the error messages built into them. I obviously put the functions on the top of the registration form so when there is an error the errors are posted on the registration form. However, I have no control on how the error messages look and would like to know if there is a lot better way to somehow echo the error messages from outside the class so I can use some type of css or something else for better control of how they look. I hope that makes sense. Also when there is an error the user is sent back to an empty registration form. I was trying to figure out how to keep the valid information in the text boxes and just make them redo the invalid information. Here is a basic example of a validation I have done. I know its basic but I am very new to programming
function validate_password($password)
{
$valid = TRUE;
if ($password == '')
{
echo "<p> Please enter a value for the password </p>";
$valid = FALSE;
}
elseif($_POST['pwd'] !== $_POST['pwd2'])
{
echo "The passwords do not match please try again";
$valid = FALSE;
}
return $valid;
}
Don't echo them right away, instead store them for later use. You mentioned this is inside a class, so you can use a class property to hold error messages.
class YourClass
{
public $error;
function validate_password($password)
{
$valid = TRUE;
if ($password == '')
{
// Set the error message
$this->error = "Please enter a value for the password";
$valid = FALSE;
}
// etc...
}
}
Later, when you need to, you can output it in the HTML:
if (!empty($yourclass->error)) {
echo "<p class='errmsg'>{$yourclass->error}</p>\n";
}
You then just need a CSS class errmsg and you can style it how you like:
.errmsg {
color: #FF0000;
font-size: 36px;
}
Now if you have that working, you can expand it further to make the $error class property into an array and push multiple messages onto it:
// In the class, initialize it as an array
$this->error = array();
// Use the [] notation to append messages to the array.
$this->error[] = "Another error message..."
$this->error[] = "And yet another error message..."
In your presentation code, use a loop to output the messages:
// Output a big stack of error messages...
foreach ($yourclass->error as $err) {
echo "<p class='errmsg'>$err</p>\n";
}
What I normally do with classes and their errors is have a variable specifically for the errors.
So something like:
class User
{
private $_ValidationErrors = array();
function validate_password($password)
{
$this->_ValidationErrors = array();
$valid = TRUE;
if ($password == '')
{
$this->_ValidationErrors[] = "Please enter a value for the password";
$valid = FALSE;
}
elseif($_POST['pwd'] !== $_POST['pwd2'])
{
$this->_ValidationErrors[] = "The passwords do not match please try again";
$valid = FALSE;
}
return $valid;
}
function ValidationErrors ()
{
if (count($this->_ValidationErrors) == 0)
return FALSE;
return $this->_ValidationErrors;
}
}
Then to use:
$user = new User();
if (!$user->validate_password('somepass'))
echo implode('<BR>',$user->ValidationErrors ());
EDIT: To display errors by the user something like:
<?php
if (isset($_POST["submit"]))
{
$user = new User();
$passwordErrors = (!$user->validate_password($_POST["pass1"]))?$user->ValidationErrors():array();
}
?>
<form action="<?php echo $_SERVER["php_self"]; ?>" method="post">
<input type="text" name="pass1" value="<?php echo htmlspecialchars($_POST["pass1"]); ?>" /><BR/>
<?php
echo ((isset($passwordErrors) && count($passwordErrors) == 0)?"":implode("<BR/>", $passwordErrors));
?>
<input type="submit" name="submit" value="Register" />
</form>

Categories