I'm trying to create my custom validation which is customer ID is required if certain option is selected. Right now, I just want to test if the custom validation is working so I don't care about the options and only set message and always return false. I don't want to put the validation in my controller for MVC pattern reason. It doesn't work if my custom validation is put in model, so I created a new validation file in libraries folder called MY_Form_validation.
MY_Form_validation.php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation
{
protected $CI;
function __construct($rules = array())
{
parent::__construct($rules);
}
public function customer_required($str)
{
$this->set_message('customer_required', 'Customer is required if you choose option A');
return false;
}
}
in model, I call it like this:
public function save()
{
/* other form validation */
$this->form_validation->set_rules('customer_id', 'Customer', 'customer_required');
return $this->form_validation->run();
}
I also put it in autoload
$autoload['libraries'] = array('session','database','table','form_validation', 'MY_Form_validation');
It should always fail to save because the validation only return false. But it looks like the custom validation is not executed at all because it always return true. Is there something that I missed? It's been days and I still don't know where I did wrong. Please help.
Update
As Marleen suggested, I tried using callable but again, function check_customer doesn't seem executed because I have a successful save.
Customer_model
$this->form_validation->set_rules('customer_is_required', array($this->customer_model, 'check_customer'));
$this->form_validation->set_message('customer_is_required', 'Customer is required of you choose option A');
private function check_customer()
{
return false;
}
Your method is not being triggered because your customer_id field is submitted empty. Codeigniter does not validate empty fields unless the rule is one of required/isset/matches or a callback or a callable. (See Form_validation.php line 700.)
If you specify your rule as a callable it can remain in the model and will be executed, even if the field is submitted empty:
$this->form_validation->set_rules('customer_id', 'Customer', array(
array($this->your_model, 'customer_required')
));
(See also: https://codeigniter.com/userguide3/libraries/form_validation.html#callable-use-anything-as-a-rule )
$this->form_validation->set_rules('customer_is_required', 'Customer', array(
array($this->customer_model, 'check_customer')
));
public function check_customer($str) {
return false;
}
And to add the message, use:
$this->form_validation->set_rules('customer_is_required', 'Customer', array(
array('customer_is_required', array($this->customer_model, 'check_customer'))
));
$this->form_validation->set_message('customer_is_required', 'Customer is required of you choose option A');
Related
In my CI4 learning, I have started by trying to simulate user sign in functionality. I have a Controller, two Views (not shown here, but really simply pages- one a pretty much just single form, and the other one a “blank” success HTML page), a set of custom rules in the Validation.php file, and a CustomRule.php file with the first of the methods that will implement all my custom rules (which, ultimately, I’d like to have all set in the Validation.php file). For lack of a better idea, I’ve stuck the CustomRules.php file in the app\Config\ folder.
Here is my problem:
For the life of me, I can’t figure out how to get the Validation service to pass additional parameters (from the form) to my custom rules function called ‘user_validated’. The CI4 documentation describes what the custom function needs to cater for when accepting additional parameters, but not how to trigger the Validation service to pass these additional parameters to one’s custom function… so although ‘user_validated’ is called, only ‘user_email_offered’ is ever passed as in as a string- nothing else goes in, from what I can tell. How do I get around this?
I have tried inserting < $validation->setRuleGroup('user_signin'); > before the call to validate, but found that I could move the setting of the rule group into the call to validate, using: $validationResult = $this->validate('user_signin'), which seemed to do the same, and which doesn't seem to work without the rule-group as a parameter (?). This still doesn't seem to be what triggers the additional data to be passed to the custom rule's method.
Extracts from my hack are appended below.
I’d be very grateful one of you knowledgeable folk could please point me in the right direction.
In app\Controllers\SignupTest.php:
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
class SignupTest extends BaseController
{
public function index() { // redirection from the default to signup(), signin(), ...
return $this->signup();
}
public function signup() {
helper(['form']);
$validation = \Config\Services::validation();
if ($this->request->getPost()) { // still TBD: any different to using $this->request->getGetPost() ?
$validationResult = $this->validate('user_signin'); // set the rules to use: 'user_signin', 'user_signup'
if (!$validationResult) {
$validationErrors = $validation->getErrors();
return view('SignupTestView', $validationErrors); // redisplay simple html form view with list of validation errors
} else {
return view('SignupTestViewSuccess'); // display view to show success
}
} else {
return view('SignupTestView'); // initial display, in the event of there being no POST data
}
}
}
In \app\Config\CustomRules.php:
<?php
namespace Config;
use App\Models\UserModel;
//--------------------------------------------------------------------
// Custom Rule Functions
//--------------------------------------------------------------------
class CustomRules
{
public function user_validated(string $str, string $fields = NULL, array $data = NULL, string &$error = NULL) : bool{
$user_email_offered = $str;
$user_password_offered = ''; // to be extracted using $fields = explode(',', $fields), but $fields is never provided in the call to this user_validated method
if (($user_email_offered !== NULL) && ($user_password_offered !== NULL)) {
$usermodel = new UserModel(); // intended to create a UserEntity to permit connectivity to the database
$user_found = $usermodel->find($user_email_offered); // we're going to assume that user_email is unique (which is a rule configured in the database table)
if ($user_found === NULL) { // check if user exists before doing the more involved checks in the else-if section below, which may throw exceptions if there's nothing to compare (?)
...
}
}
In \app\Config\Validation.php:
?php
namespace Config;
class Validation
{
//--------------------------------------------------------------------
// Setup
//--------------------------------------------------------------------
/**
* Stores the classes that contain the
* rules that are available.
*
* #var array
*/
public $ruleSets = [
\CodeIgniter\Validation\Rules::class,
\CodeIgniter\Validation\FormatRules::class,
\CodeIgniter\Validation\FileRules::class,
\CodeIgniter\Validation\CreditCardRules::class,
\Config\CustomRules::class,
];
/**
* Specifies the views that are used to display the
* errors.
*
* #var array
*/
public $templates = [
'list' => 'CodeIgniter\Validation\Views\list',
'single' => 'CodeIgniter\Validation\Views\single',
];
//--------------------------------------------------------------------
// Custom Rules
//--------------------------------------------------------------------
/* configurable limits for validation rules array below*/
const user_email_min_lenth = 9;
const user_email_max_lenth = 50;
const user_password_min_lenth = 6;
const user_password_max_lenth = 25;
public $user_signin = [
'user_email' => [
'label' => 'e-mail address',
'rules' => 'trim|required|valid_email|user_validated', // user_validated is custom rule, that will have a custom error message
'errors' => [
'required' => 'You must provide an {field}',
'valid_email' => 'Please enter a valid {field}',
]
],
'user_password' => [
'label' => 'password',
'rules' => 'trim|required',
'errors' => [
'required' => 'Enter a {field} to sign in',
'user_password_check' => 'No such user/{field} combination found',
]
Calling custom rule with parameters should be exactly the same as calling CI4's regular rules. Let's get for example "required_without". You use it like in this example:
$validation->setRule('username', 'Username', 'required_without[id,email]');
And the function is declared as so:
public function required_without($str = null, string $fields, array $data): bool
{
$fields = explode(',', $fields);
//...
}
where $str - this is your main field, $fields - string, packing a comma-separated array.
As for Grouping rules, you do not need to group rules to be able to use custom rules with parameters.
If you have only 2 fields to test against you can go a bit cheaper, which will not be perfect but still works:
Function:
public function myrule(string $mainfield, string $fieldtotestwith): bool
{
//doing stuff
}
Validating rule:
$validation->setRule('somemainfield', 'Something', 'myrule[somesecondfield]');
For validating form validation rules I currently stored them in User Model and use it in Register Controller, User controller in admin panel, User Controller in APIs and some other places, but currently it's very hard to maintain because each controller needs a slightly different set of rules and when I change the rules in User Model other controllers will not work anymore. So how to avoid duplication in rules and still keep the code maintainable?
Approach I often use is to write a HasRules trait for my models, it looks something like this:
trait HasRules
{
public static function getValidationRules(): array
{
if (! property_exists(static::class, 'rules')) {
return [];
}
if (func_num_args() === 0) {
return static::$rules;
}
if (func_num_args() === 1 && is_string(func_get_arg(0))) {
return array_get(static::$rules, func_get_arg(0), []);
}
$attributes = func_num_args() === 1 && is_array(func_get_arg(0))
? func_get_arg(0)
: func_get_args();
return array_only(static::$rules, $attributes);
}
}
Looks messy, but what it does is allows you to retrieve your rules (from a static field if such exists) in a variety of ways. So in your model you can:
class User extends Model
{
use HasRules;
public static $rules = [
'name' => ['required'],
'age' => ['min:16']
];
...
}
Then in your validation (for example, in your FormRequest's rules() method or in your controllers when preparing rules array) you can call this getValidationRules() in variety of ways:
$allRules = User::getValidationRules(); // if called with no parameters all rules will be returned.
$onlySomeRules = [
'controller_specific_field' => ['required'],
'name' => User::getValidationRules('name'); // if called with one string parameter only rules for that attribute will be returned.
];
$multipleSomeRules = User::getValidationRules('name', 'age'); // will return array of rules for specified attributes.
// You can also call it with array as first parameter:
$multipleSomeRules2 = User::getValidationRules(['name', 'age']);
Don't be afraid to write some code for generating your custom controller specific rules. Use array_merge and other helpers, implement your own (for example, a helper that adds 'required' value to array if it's not there or removes it etc). I strongly encourage you to use FormRequest classes to encapsulate that logic though.
You can try using laravel's validation laravel documentation
it is really easy to use and maintain just follow these steps:
run artisan command: php artisan make:request StoreYourModelName
which will create a file in App/Http/Requests
in the authorize function set it to:
public function authorize()
{
return true;
}
then write your validation logic in the rules function:
public function rules()
{
return [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
];
}
Custom error messages add this below your rules function:
public function messages()
{
return [
'title.required' => 'A title is required',
'body.required' => 'A message is required',
];
}
Lastly to use this in your controller just add it as a parameter in your function.
public function create(Request $request, StoreYourModelName $storeYourModelName)
{
//
}
and that's all you need to do this will validate on form submission if validation passes it will go to your controller, keep in mind your validation logic does not have to be like mine thought i would show you one way that it can be done..
I have a number of fieldsets, and I would like to create an input filter class for each of them. The idea is then that for each of my forms, I can create an input filter class that is composed of other input filters. For instance, when creating an account via a registration form, I would like to take the base Account input filter I have for my Account entity and use it in a new input filter class that can modify the inputs or add additional ones. Something like the below.
class Register extends InputFilter
{
public function __construct(ObjectRepository $accountRepository, Account $accountFilter)
{
/***** Add inputs from input filters *****/
$this->inputs = $accountFilter->getInputs();
/***** Add additional validation rules *****/
// Username
$usernameAvailability = new NoObjectExists(array(
'object_repository' => $accountRepository,
'fields' => array('username'),
));
$username = $this->get('username');
$username->getValidatorChain()
->attach($usernameAvailability, true);
// E-mail
$emailAvailability = new NoObjectExists(array(
'object_repository' => $accountRepository,
'fields' => array('email'),
));
$email = $this->get('email');
$email->getValidatorChain()
->attach($emailAvailability, true);
}
}
I pass in an input filter to the constructor, and I want to add the inputs of this filter to my Register filter and modify the inputs.
The problem I am having is that only some of my inputs seem to validate as intended, and I cannot seem to figure out why. When I submit my form, only some inputs are validated as expected:
Interestingly, the e-mail input does not behave as expected when filling out an e-mail that already exists in my database. The result should be a validation error that it already exists, but this does not happen. If I debug and look at my form, I found the following:
The form's filter has the right inputs with the right validators, and as shown on the above image, the username input does seem to validate correctly. But for some reason, this is not visually reflected in my form.
Below is my code.
Fieldsets
class Profile extends Fieldset
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct('profile');
$this->setHydrator(new DoctrineHydrator($objectManager))
->setObject(new ProfileEntity());
// Elements go here
$this->add(new AccountFieldset($objectManager));
}
}
class Account extends Fieldset
{
public function __construct()
{
parent::__construct('account');
$username = new Element\Text('username');
$username->setLabel('Username');
$password = new Element\Password('password');
$password->setLabel('Password');
$repeatPassword = new Element\Password('repeatPassword');
$repeatPassword->setLabel('Repeat password');
$email = new Element\Email('email');
$email->setLabel('E-mail address');
$birthdate = new Element\DateSelect('birthdate');
$birthdate->setLabel('Birth date');
$gender = new Element\Select('gender');
$gender->setLabel('Gender')
->setEmptyOption('Please choose')
->setValueOptions(array(
1 => 'Male',
2 => 'Female',
));
$this->add($username);
$this->add($password);
$this->add($repeatPassword);
$this->add($email);
$this->add($birthdate);
$this->add($gender);
$this->add(new CityFieldset());
}
}
Form
class Register extends Form
{
public function __construct()
{
parent::__construct('register');
// Terms and Conditions
$terms = new Element\Checkbox('terms');
$terms->setLabel('I accept the Terms and Conditions');
$terms->setCheckedValue('yes');
$terms->setUncheckedValue('');
$terms->setAttribute('id', $terms->getName());
// Submit button
$submit = new Element\Submit('btnRegister');
$submit->setValue('Register');
$profileFieldset = new ProfileFieldset($objectManager);
$profileFieldset->setUseAsBaseFieldset(true);
// Add elements to form
$this->add($terms);
$this->add($profileFieldset);
$this->add($submit);
}
}
View
$form->prepare();
echo $this->form()->openTag($form);
$profile = $form->get('profile');
$account = $profile->get('account');
echo $this->formRow($account->get('username'));
echo $this->formRow($account->get('password'));
echo $this->formRow($account->get('repeatPassword'));
echo $this->formRow($account->get('email'));
echo $this->formRow($account->get('birthdate'));
echo $this->formRow($account->get('gender'));
$city = $account->get('city');
echo $this->formRow($city->get('postalCode'));
echo $this->formRow($form->get('terms'));
echo $this->formSubmit($form->get('btnRegister'));
echo $this->form()->closeTag();
Controller
$form = new Form\Register();
$profile = new Profile();
if ($this->request->isPost()) {
$form->bind($profile);
$form->setData($this->request->getPost());
$form->setInputFilter($this->serviceLocator->get('Profile\Form\Filter\Register'));
if ($form->isValid()) {
// Do stuff
}
}
return new ViewModel(array('form' => $form));
Am I misunderstanding something here? Is there a better way to do this while still having multiple input filter classes? I would really prefer to keep my code maintainable like this rather than copying validation rules around for different forms. Sorry for the long post - it was really difficult to explain this problem!
Okay, it seems like I figured this out. Apparently my first approach was quite wrong. I found a way to have an input filter class for each of my fieldsets and then reuse these input filters for my form while adding additional validation rules for certain form elements (from my fieldsets). This way, I can have my generic validation rules defined in standard input filter classes per fieldset and modify them for different contexts (i.e. forms). Below is the code. The classes differ a bit from the question because that was slightly simplified.
Main input filter
// This input filter aggregates the "fieldset input filters" and adds additional validation rules
class Register extends InputFilter
{
public function __construct(ObjectRepository $accountRepository, InputFilter $profileFilter)
{
/***** ADD ADDITIONAL VALIDATION RULES *****/
// Username
$usernameAvailability = new NoObjectExists(array(
'object_repository' => $accountRepository,
'fields' => array('username'),
));
$emailInput = $profileFilter->get('account')->get('username');
$emailInput->getValidatorChain()->attach($usernameAvailability, true);
// E-mail
$emailAvailability = new NoObjectExists(array(
'object_repository' => $accountRepository,
'fields' => array('email'),
));
$emailInput = $profileFilter->get('account')->get('email');
$emailInput->getValidatorChain()->attach($emailAvailability, true);
/***** ADD FIELDSET INPUT FILTERS *****/
$this->add($profileFilter, 'profile');
}
}
Profile input filter
class Profile extends InputFilter
{
public function __construct(InputFilter $accountFilter)
{
$this->add($accountFilter, 'account');
// Add generic validation rules (inputs) for the profile fieldset here
}
}
The Account input filter referred to in the code above is a completely normal input filter class that extends Zend\InputFilter\InputFilter and adds inputs. Nothing special about it.
My fieldsets remain untouched and are identical to the ones in the question, as are the form class and the controller. The Register input filter is added to the form with the setInputFilter method, and that's it!
With this approach, each input filter instance is added to a fieldset - something that my first approach did not do. I hope this helps someone with similar problems!
I have a User entity with some validators specified in it.
But I want to extend that list of validators so as to add one based on a service call to check if a user email is not already used.
The problem is that I need an entity manager injected in the validator to call the service. And I can't (or rather don't know how to and don't want to :-) inject the entity manager into the entity.
I also want to leave in place the existing validation on the entity, as it is closer to the repository and might be used outside of my controller. So I cannot move all the validators out of this entity, into my new custom filter.
My new custom filter thus shall reuse the existing validators of the entity, as is.
The new custom filter is called UserFormFilter and it receives in its controller the existing entity filter, loops on it, adding to itself, each of the passed in validators:
class UserFormFilter extends InputFilter
{
public function __construct(EntityManager $em, $identity, InputFilter $userDefaultInputFilter)
{
// Add the validators specified in the user entity
foreach ($userDefaultInputFilter->inputs as $inputFilter) {
$this->add($inputFilter);
}
$this->add(array(
'name' => 'email',
'required' => true,
'filters' => array(),
'validators' => array(
array('name' => 'EmailAddress'),
array(
'name' => 'Application\Validator\User',
'options' => array('manager' => $em, 'identity' => $identity)
)
),
));
}
}
I can now instantiate a custom UserFormFilter in my UserController:
$formFilter = new \Application\Form\UserFormFilter($em, $user->getInputFilter());
$form->setInputFilter($formFilter);
You can see in the above code that the custom UserFormFilter takes the default filter specified in my User entity getInputFilter method. As a side note, it also passes the entity manager enabling the custom filter to carry out the service call.
I'm trying to figure out how I can use the is_unique rule from the Codeigniter form validation library in the following situation.
I'm trying to submit a edit user form and have the rule:
$this->form_validation->set_rules('user_name', 'User Name', 'required|trim|xss_clean|is_unique[users.user_name]');
What if other values in the form are being changed but this value stays the same. The form is going to see that this value already exists so how would I protect it from editing if this value isn't changed.
Using your code as an example, the is_unique validation rule works by looking for a field called user_name in your users database table. If the field with the same value exists it validates as false.
To make sure it runs only when the user submits a new value, you could check the posted value $this->input->post('user_name') against the value you pulled from the database to populate your form with. If they are the same, don't validate is_unique;
if($this->input->post('user_name') != $original_value) {
$is_unique = '|is_unique[users.user_name]'
} else {
$is_unique = ''
}
$this->form_validation->set_rules('user_name', 'User Name', 'required|trim|xss_clean'.$is_unique);
There's a better way to go around it, I think, still using CodeIgniters' validation library...
Use edit_unique where you pass an extra parameter which is the id of the row you're editing.. See below.. I use it and works pretty fine for me.. hope it helps
$this->form_validation->set_rules('user_name', 'User Name', 'required|trim|xss_clean|edit_unique[users.user_name.'.$id.']');
$something = $this->input->post('something');
$this->form->validation->set_rules('something','Something','xss_clean|is_unique['tbl'.users]');
if($this->form_validation->run()== FALSE){
}
Simple Way
Just Change isset to is_object in system/libraries/form_validation.php
public function is_unique($str, $field)
{
sscanf($field, '%[^.].%[^.]', $table, $field);
return is_object($this->CI->db) //default isset
? ($this->CI->db->limit(1)->get_where($table, array($field => $str))->num_rows() === 0)
: FALSE;
}
Here's an easy method that worked for me and uses well documented code (thanks to https://github.com/ivantcholakov for sharing it!). I found it referenced at https://github.com/bcit-ci/CodeIgniter/issues/3109#issuecomment-46346280
Download https://github.com/ivantcholakov/starter-public-edition-3/blob/master/platform/application/libraries/MY_Form_validation.php (MIT licensed) and save it to your application at application\libraries\MY_Form_validation.php
Delete these two lines from __construct():
$this->CI->load->helper('checkbox');
$this->CI->load->helper('email');
Delete all the functions except __construct() and unique().
At the end of the __construct() method of your controller add this line:
$this->load->library('form_validation');
As per the documentation of the unique() method update your validation rule to add a "unique" rule like this (e.g. if you already have required and trim rules):
…|required|unique[tablename.fieldname,tablename.(primaryKey-used-for-updates)]|trim...
Extend Form_validation.php library create class inside of application/libraries file name MY_Form_validation.php
<?php
class MY_Form_validation extends CI_Form_validation{
protected $ci;
public function __construct($config = array()){
parent::__construct($config);
$this->ci =& get_instance();
}
public function is_unique_update($str, $field){
$explode=explode('#', $field);
$field_name=$explode['0'];
$field_id_key=$explode['1'];
$field_id_value=$explode['2'];
sscanf($field_name, '%[^.].%[^.]', $table, $field_name);
if(isset($this->ci->db)){
if($this->ci->db->limit(1)->get_where($table, array($field_name => $str,$field_id_key=>$field_id_value))->num_rows() === 0){
$this->ci->form_validation->set_message('is_unique_update', 'The {field} field must contain a unique value.');
return false;
}
return true;
}
}
}
Now in your controller
$this->form_validation->set_rules('user_name', 'User Name', 'required|trim|xss_clean|is_unique_update[users.user_name#id#'.$id.']');
"#" I used for explode the string
where id is primary key of users table
and $id is the value of id.
Now you can use this is_unique_update validation in any controller.
This question is very old but maybe some new people experience this problem and this is the solution for it.
I bet your are using Modular Extensions (HMVC) and you have created a new library, MY_Form_validation. You did id for callbacks, so you have this line of code on your class in order to use callbacks:
$this->form_validation->CI =& $this;
Well, the solution to this is whenever you want to use "is_unique" you must delete this line of code "$this->form_validation->CI =& $this;" from the class. I have experienced this problem and i fix it this way, it works fine now.
If you realy want to use callbacks "$this->form_validation->CI =& $this;", then do it only on required "methods" / "functions" where you don't want to use is_unique.
This code helpful for unique validation to create and update function...
In controller
Add this form validation code in both create and update function
$this->form_validation->set_rules('order_no', 'Order no', 'required|callback_check_order_no');
Add this call back function in controller
function check_order_no($order_no) {
if($this->input->post('id'))
$id = $this->input->post('id');
else
$id = '';
$result = $this->Data_model->check_unique_order_no($id, $order_no);
if($result == 0)
$response = true;
else {
$this->form_validation->set_message('check_order_no', 'Order no already exist');
$response = false;
}
return $response;
}
In model
function check_unique_order_no($id = '', $order_no) {
$this->db->where('order_no', $order_no);
$this->db->where('status', "A");
if($id) {
$this->db->where_not_in('id', $id);
}
return $this->db->get('delivery_order')->num_rows();
}
I'm using codeigniter3 and it shows me error when I check username on updating the value, is_unique is not designed to work with update scenario
so using #Anthony Mutisya's answer, here is the complete solution
in your controller, add this line while validation username of the current user with the database
$this->form_validation->set_rules('user_name', 'User Name', 'required|trim|xss_clean|edit_unique[users.user_name.'.$id.']');
You can get that $id from your submited form.
Now, add the following function to /system/libraries/Form_Validation.php this file. System folder is present in your root of CodeIgniter3 folder.
/**
* edit_unique // for check on update value
*
* Check if the input value doesn't already exist
* in the specified database field.
*
* #param string $str
* #param string $field
* #return bool
*/
function edit_unique($value, $params) {
$CI =& get_instance();
$CI->load->database();
$CI->form_validation->set_message('edit_unique', "Sorry, that %s is already being used.");
list($table, $field, $current_id) = explode(".", $params);
$query = $CI->db->select()->from($table)->where($field, $value)->limit(1)->get();
if ($query->row() && $query->row()->id != $current_id)
{
return FALSE;
} else {
return TRUE;
}
}
It works perfectly fine in my case
CodeIgniter 4 has already solution for that,
$validation->setRules([
'email' => 'required|valid_email|is_unique[users.email,id,{id}]',
]);
$_POST = [
'id' => 4,
'email' => 'foo#example.com',
];
then the {id} placeholder would be replaced with the number 4, giving this revised rule:
$validation->setRules([
'email' => 'required|valid_email|is_unique[users.email,id,4]',
]);
Official Documentation
we must have to add table name for is_unique
for Exp.
is_unique[users.email]
There is a 'main.php' view that contains a form with email and name fields and a submit button. Eveyrthing works fine with action_index (the code is below), but I'm curious how to modify the code below so it validates if the email was entered correctly. It should not put values in the database if the email field is not valid. I hope it is possible to made using ->rule. Is it? If yes, then how where to add the validation? (I had no luck trying it in different ways).
public function action_index()
{
if ( !empty($_POST) ) {
$model = ORM::factory('tbl1'); // create
$model->values($_POST); // load values to model
if ($model->check()) {
$model->save(); // save the model
} else {
//show errors
}
}
$this->response->body(View::factory('main'));
}
Thank you.
Use rules function in your ORM model:
public function rules()
{
return array(
'email' => array(
array('email', array(':value')),
),
);
}