catch always get called - php

I'm having problem saving data to the database since catch exception is always being called. try always get ignored. I don't really know what's happening. I've been working for this for hours and I can't get it to work. I'm using kohana 3.3 and kostache.
So here's the controller.
Controller
APPATH/classes/controller/album.php
public function action_create()
{
$view = Kostache_Layout::factory();
$layout = new View_Pages_Album_List();
$album = ORM::factory('Album_Information');
$album_name = $this->request->post('inputAlbum');
$artist = $this->request->post('inputArtist');
$album->Album_Name = $album_name;
$album->Artist = $artist;
try
{
$album->save();
HTTP::redirect('album');
}
catch(ORM_Validation_Exception $e)
{
$layout->errors = $e->errors('models');
}
}
$this->response->body($view->render($layout));
}
Templates
APPATH/templates/pages/album/list.mustache
<h3>Add A New Album</h3>
<form action="album/create" method="post">
<label for="inputAlbum">Album Name:</label>
<input id="inputAlbum" type="text" name="inputAlbum" /><br />
<label for"inputAlbum" class="error">{{#errors}}{{inputAlbum}}{{/errors}}</label>
<label for="inputArtist">Album Artist:</label>
<input id="inputArtist" type="text" name="inputArtist" /><br />
<label for="inputArtist" class="error">{{#errors}}{{inputArtist}}{{/errors}}</label>
<input type="submit" name="submit" value="Add" />
</form>
Model Rules
APPATH/classes/model/album/information.php
class Model_Album_Information extends ORM
{
protected $_primary_key = 'ID';
protected $_table_name = 'album_information';
public function rules()
{
return array(
'inputAlbum' => array(
array('not_empty'),
),
'inputArtist' => array(
array('not_empty'),
),
);
}
Messages
APPATH/messages/models/album.php
return array(
'inputAlbum' => array(
'not_empty' => ':You must provide Album Name',
),
'inputArtist' => array(
'not_empty' => ':You must provide Album Artist',
),
);
The errors are showing when there's no input on the input field when i hit on the submit button, no problem with that, but even there's an input the errors are still being shown. So catch is always being called. When i remove try and catch I can easily save data to the database but there's no validation.
Thank you and more power.

You expect the ORM class to magically know the value of $album->Album_Name came from a HTTP form input named inputAlbum. It won't.
Create rules for the Album_Name and Artist properties of the ORM object itself. Not the possible input method.
The Controller knows what data to pass to models. The Model is only concerned with the data it received. Not where it came from.

Related

How to apply validation on any single field having same name Laravel?

I have a project that consists of multilingual functionality. So I'm creating a form that consists of multiple languages to be inserted if User wants.
But validation should be like if any of the fields having the same name consist value then leave rest one like as
Form
<form>
<input type="text" name="name[EN]" />
<input type="text" name="name[AR]" />
<input type="text" name="name[FR]" />
<input type="submit" value="submit" />
</form>
Now I want to validate that if any one of these fields have value then submit form else throw a validation
So I've tried Laravels required_if, but it didn't work.
public function rules()
{
return [
'name.*' => 'required_if:name,1',
];
}
So how to make such validation in laravel
I've searched but could not find a built in way of doing this. You can create your own rule using
php artisan make:rule NonEmptyFiltered
and then define the rule as:
class NotEmptyFiltered implements Rule {
public function passes($attribute, $value) {
return !empty(array_filter($value));
}
public function message() {
return ':attribute must have at least one non-null element';
}
}
You can then do:
public function rules()
{
return [
'name' => [ new NonEmptyFiltered() ]
];
}
I believe this should do the trick:
$rules = [
'name.EN' => 'required_without_all:name.AR,name.FR',
'name.AR' => 'required_without_all:name.EN,name.FR',
'name.FR' => 'required_without_all:name.EN,name.AR',
];
The rule makes the field to be required if the other fields are empty https://laravel.com/docs/5.6/validation#rule-required-without-all.

How do I use CodeIgniter's `set_value()` function when using `form_validation.php`?

Problem:
I've got a form I'm trying to re-populate via the CodeIgniter docs, and I'm trying to use the set_value() function in my view file, but I receive an error: Message: Call to undefined function set_value().
I saw elsewhere on StackOverflow solutions to a similar problem when using the set_rules() function to define validations on a field-by-field basis.
However, I've got all of my validations together in config/form_validation.php, as sets of rules. Because all of my validations are defined within the rule set, it seems a little different than when defining field-by-field.
My rule set, controller, model and view methods are below.
Any idea why my re-population is not working?
Thanks for any insight anyone can offer, I'm new to CodeIgniter and I might be misunderstanding how things are working.
Validation Rules via config/form-validation.php:
$config = array(
'create' => array (
array(
'field' => 'name',
'label' => 'product name',
'rules' => 'trim|required|min_length[5]',
),
array(
'field' => 'description',
'label' => 'product description',
'rules' => 'trim|required|min_length[5]',
),
array(
'field' => 'price',
'label' => 'product price',
'rules' => 'trim|required|min_length[1]|less_than[100000]|decimal',
),
),
);
In my Controller:
public function create()
{
// XSS FILTER $POST OBJECT
$new_product = $this->input->post(null, true);
// SEND TO MODEL
$this->load->model("Product_model");
$product = $this->Product_model->add_product($new_product);
// IF VALIDATIONS RETURN FALSE, STORE ERRORS IN FLASH SESSION
if ($product[0] === FALSE)
{
$this->session->set_flashdata('errors', $product[1]);
redirect("/products/new");
}
// IF VALIDATION PASSES, SEND HOME
redirect("/");
}
In my Model:
public function add_product($product)
{
$this->load->library("form_validation");
if ($this->form_validation->run("create") === FALSE)
{
// STORE ERRORS & SHIP BACK TO CONTROLLER:
return array(FALSE, validation_errors());
}
else
{
// Success, Escape strings and insert to DB and return TRUE (or item)
}
}
In my form View:
(The page which displays returned errors above the form)
<form action="./create" method="POST">
<input type="text" name="name" id="name" value="<?php echo set_value('name'); ?>">
<textarea name="description" id="description" cols="30" rows="10" value="<?php echo set_value('description'); ?>"></textarea>
<input type="number" name="price" id="price" value="<?php echo set_value('price'); ?>">
<input type="submit" value="Create">
</form>
Hope this will help you :
add form_helper in your controller or in autoload.php
In controller :
public function __construct()
{
parent::__construct();
$this->load->helper('form');
}
Or in autoload.php :
$autoload['helper'] = array('form','url');
For more : https://www.codeigniter.com/userguide3/libraries/form_validation.html#re-populating-the-form

How do I echo the variables that I passed by post with the codeIgniter framework MVC

I am trying to save the data from the form into the database but I can't do that... Don't know why. I want to print the variables and see if the variables are being passed via post. How do I echo the variables passed via post and where. I'm new to the MVC model.
So in my view I have (inside a form):
<td>
<input size="15" type="text" name="val1" id="val1" class="text" value="<?= isset($user) ? set_value('val1',$this->form_validation->val1) : set_value('val1'); ?>"/>
<?= form_error('val1');?>
</td>
<td>
<input size="15" type="text" name="val2" id="val2" class="text" value="<?= isset($user) ? set_value('val2',$this->form_validation->val2) : set_value('val2'); ?>"/>
<?= form_error('val2');?>
</td>
<td>
<input size="15" type="text" name="val3" id="val3" class="text" value="<?= isset($user) ? set_value('val3',$this->form_validation->val3) : set_value('val3'); ?>"/>
<?= form_error('val3');?>
</td>
then in my controller:
if($this->input->post('val3')!=''){
$data = array(
'id_val' => $id,
'pass' => $this->input->post('oldVal'),
'newPass'=> $this->input->post('newVal'),
'user' => $this -> session ->userdata('username')
);
$id_m = $this->val3_model->save($data);
}
if($this->input->post('val1')!=''){
$data = array(
'id_val' => $id,
'pass' => $this->input->post('oldVal'),
'newPass'=> $this->input->post('newVal'),
'user' => $this -> session ->userdata('username')
);
$id_m = $this->val1_model->save($data);
}
if($this->input->post('val2')!=''){
$data = array(
'id_val' => $id,
'pass' => $this->input->post('oldVal'),
'newPass'=> $this->input->post('newVal'),
'user' => $this -> session ->userdata('username')
);
$id_m = $this->val2_model->save($data);
}
model:
class Val1_model_model extends CI_Model{
// table name
private $table= 'val1';
function _construc(){
parent::Model();
}
*
*
*
function save($data){
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
}
At the very beginning of the controller method, you can use var_dump();
var_dump($this->input->post(NULL, TRUE));
The Input::post() method returns data in the $_POST array. Assuming your form uses that method and it posts to that controller/method, this should print the contents of the $_POST array. The first argument allows to specify a specific index (field name), but if you pass NULL (or nothing, eg. $this->input->post()) you will get the entire array of values. The second argument runs it all through a XSS filter, which is desirable.
#AVProgrammer gives you a great way to dump the whole post.
If that doesn't work, you might be doing a few things wrong. First, if you have an action attribute on your form, verify that is is correct. Here is a good article to explain more.
That aside, to answer your specific question, here is an example of outputting the variable in the view itself (after the post):
<?php if ($this->input->post('val3')) { echo $this->input->post('val3'); } ?>
Hope this helps.

Error: You must use the "set" method to update an entry fix?

I am using codeigniter as my PHP framework, and I keep getting this error when I submit my from to post to my database.
You must use the "set" method to update an entry
I am not exactly sure what that means, from the other posts I have looked at, everyone says that the datamapper needs to have a value assigned to the object.
Being that I am new to all this, could someone give me a better explaniation.
Here is my code where it says I have the error:
class Add_book extends CI_Model {
public function add_book($data){
$this->db->insert('ST_ITM', $data);
}
}
?>
Thank you.
You need to do something like this Example Only
class Add_book extends CI_Model {
public function add_book(){
// 'book_name' would be the name of your column in database table
$data = array(
'book_title' => $this->input->post('book_title'),
'book_author' => $this->input->post('book_author'),
'book_name' => $this->input->post('book_name')
);
$this->db->set($data);
$this->db->insert($this->db->dbprefix . 'ST_ITM');
}
}
On view the input would be like example
<input type="text" name="book_name" value="" />
<input type="text" name="book_title" value="" />
<input type="text" name="book_author" value="" />
Best to use a data array in model. and then load model function in success part of form validation Library
To all who arrive here, you do NOT have to use set in your insert queries:
https://www.codeigniter.com/userguide3/database/query_builder.html#inserting-data
$data = array(
'title' => 'My title',
'name' => 'My Name',
'date' => 'My date'
);
$this->db->insert('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
The error is a result of misconstructed insert data (must be an array) or failing to write the correct Active Record query like for example not adding the table name before the insert array.
But sir, when do we use set?
When you need to bypass automatic escaping during updates or replacings for example:
$this->db->set('last_login', 'NOW()', FALSE);
$this->db->update(DB_PREFIX .'user', array('login_attempts' => 0));
The third parameter disabled auto-escaping. This gives us the necessary flexibility when writing Active Record queries.
I got this error when i was passing wrong variable into the insert statement.
For example :
function($a){
$this->db->insert($aa); <-- error !!
}
So I solved it by passing in the right variable, which is $a.
Also make sure your insertion array is correctly formatted as $a = array('columnname'=>'value');
For Example I want to insert data, so I have to do code like below -
My View File(Login_form.php)
<label>Username:</label> <input type="text" name="username" value="">
<label>Password:</label> <input type="password" name="password" value="">
My Model File(Model_login.php)
class Model_login extends CI_Model {
public function insert_entry()
{
$data= array(
'username'=>$this->input->post('username'), // here username and password are database fields.
'password'=>$this->input->post('password'),
);
$this->db->insert('login', $data); //here login is my database table's name
}
}
Controller File(Login.php)
class Login extends CI_Controller {
public function index()
{
$this->load->view('Login_form'); //to load view file
}
public function getLoginValues()
{
$this->load->model('Model_login'); //to load Model file
$data=$this->Model_login->insert_entry();//to load method of Model file
}
}
It works fine, check it.
in your model.
public function SetFoo($bar) {
$data = [
'YourColumnName' => 'Yes'
];
// Using Query Builder
$this->set($data);
$this->where('id',$bar);
$this->update();
}
This will throw the above error if you do not add tot he top of the model the following
protected $allowedFields = ['YourColumnName'];
The columns can exist in the model but are not accessible using set update unless its in the allowedfields section (its like a private/public for the code to see the column)
the problem is in your model.
so you have to check if the array $data is empty or not
like this :
class Add_book extends CI_Model {
public function add_book($data){
if ( $data != null)
$this->db->insert('ST_ITM', $data);
}
}
?>

Codeigniter approach to save all posted values in bidimensional array

I have a multiform and I need to insert several values to 4 user,news,feed,lat (maybe 6) tables that are related by some ID this is because an event needs all this information.
my form:
<form method="post" action="<?php echo base_url();?>controller/save" name="event"/>
<label>User Name</label>
<!--#####FOR TABLE USER#####-->
<input type="text" name="name">
<input type="text" name="name">
<!--#####FOR TABLE NEWS#####-->
<input type="text" name="title">
<input type="submit" value="body"/>
<!--#######################
OTHER TABLE FIELDS ...
#######################
-->
<input type="submit" value="save"/>
</form>
Now I would like to pass a bidimensional array to event model and then depending on value insert to corresponding table
controller event.php
class Event extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
$this->load->model('event_model');
}
public function save()
{
/** Is it possible to fill this bidimensional array with for loops???? **/
$arr_data = array(
array("person", $this->input->post("name") , $this->input->post("address")),
array("news" , $this->input->post("title") , $this->input->post("body" )),
array("feed" , $this->input->post("id_feed") , $this->input->post("main" )),
array("lat" , $this->input->post("lat1" , $this->input->post("lat" ))
);
$this->event_model->insert_tables($arr_data);
}
}
Now How to receive the array in model and do the insert how to declare event_model?
class Event_model extends CI_Model {
function Event_model ()
{
parent::__construct();
}
function insert_tables($arr_data) {
if( "person" )
$this->db->insert(person_tb ,
}
}
Is it necessary to use implode or something, Is there a better way to do this multiple inserting?
I would do something like this...
$person = array('name' => $this->input->post("name"), 'address' => $this->input->post("address"));
$news = array('title' => $this->input->post("title"), 'body' => $this->input->post("body"));
$feed = array('id' => $this->input->post("id_feed"), 'main' => $this->input->post("main"));
$lat = array('lat1' => $this->input->post("lat1"), 'lat' => $this->input->post("lat"));
if($this->person_model->insert($person)) {
$person_id = $this->db->insert_id();
} else {
// handle the problem of not having an id for this entity...
}
if($this->news_model->insert($news)) {
$news_id = $this->db->insert_id();
} else {
// handle the problem of not having an id for this entity...
}
if ($this->feed_model->insert($feed)) {
$feed_id = $this->db->insert_id();
} else {
// handle the problem of not having an id for this entity...
}
if($this->lat_model->insert($lat)) {
$lat_id = $this->db->insert_id();
} else {
// handle the problem of not having an id for this entity...
}
Sounds really complicated...why not have a model for each entity and pass the right fields to the right model? Or create a library that inserts/updates each of your models?

Categories