Codeigniter form validation callback in model callback not working? - php

Im pretty new to this framework. The issue is that form validation callbacks are not being called inside a model. It will work inside a controller without an issue.
Am I right thinking logic/database stuff is to be inside a model rather than controller? What am I doing wrong? Im trying to do this as best as possible.
Example Model Method:
//The Callback
function check_delete()
{
$this->form_validation->set_message('check_address', 'This is a test message');
return false;
}
function test()
{
//The Check
$this->form_validation->set_rules('address_id', 'ID', 'required|callback_check_delete');
//On Success
if($this->form_validation->Run() == TRUE) {
//Do something interesting on success!
}
}

Related

How to call a function from another route in laravel php

im trying to call a function from another route in laravel php.
I have the route "welcome"
Route::get('/', function () {
return view('welcome');
});
where im calling this extends (sidebar)
#extends('layouts.guestnavbar')
i want to see if my table notifications is empty or not so i made this controller
class GuestNavbarController extends Controller
{
public function isempty(){
$notif = Notification::first();
if(is_null($notif)) {
return view('layouts.guestnavbar')->with("checkempty", "empty");
}else {
return view('layouts.guestnavbar')->with("checkempty", "not empty");
}
}
}
and i called the variable {{ $checkempty }} in my route guestnavbar
Route::get('/guestnavbar', [GuestNavbarController::class, 'isempty']);
and it works when im in the route guestnavbar
but doesnt work when im in the route welcome because i call the function in the route guestnavbar and in welcome he doesnt recognize the variable: checkempty
i need this function to be in the guestnavbar because i have to call it on other pages, not just in welcome page
I appreciate any help.
You don't need isempty inside controller, just add method isempty inside Notification model, you can use something like this inside Notification model:
public static function isEmpty(){
return Notification::first() ? true : false;
}
And then where you need to check if notification table is empty just call Notification::isEmpty()

CodeIgniter: How to put custom validation function in model instead of controller?

In CI's documentation, it says that you could create your own custom validation for use in form submission check. It shows how this can be done in a controller:
http://ellislab.com/codeigniter%20/user-guide/libraries/form_validation.html
But what if I want to have my custom validation function in a model?
I've found that the following did not work...
BOTH FUNCTIONS BELOW ARE IN A MODEL:
public function validate_form(){
$this->form_validation->set_rules('username', 'Username', 'callback_illegal_username_check');
$this->form_validation->run();
}
And here's my custom validation function:
public function illegal_username_check($string){
if($string == 'fcuk'){
$this->form_validation->set_message('illegal_username_check', 'Looks like you are trying to use some swear words in the %s field');
return FALSE;
}
else{
return TRUE;
}
}
I found that because my custom validation function is in the model, it did not get called when I run my "validate_form()" function. How do I resolve this?
Many thanks in advance!
You should put custom validation rules in a MY_Form_validation.php in the application/libraries folder.
Then, when you assign your rules you can do something like this..
$this->form_validation->set_rules('field1', 'Field one name', 'trim|required|xss_clean|your_custom_validator');
Note the custom validator doesn't require the callback_ keyword in front.
Here's an example My_Form_valdation.php file.
class MY_Form_validation extends CI_Form_validation {
function __construct($rules = array()) {
parent::__construct($rules);
$this->ci = & get_instance();
$this->ci->load->database();
}
function your_custom_validator($val) {
$this->set_message('your_custom_validator', 'this isn\'t right!');
return (!$val) ? FALSE : TRUE;
}
Note in the construct I've got the Ci instance and loaded the database class.
To use it i'd do something like this..
$this->ci->db->where('id', 1)->get('user')->row();

In Zend Framework 1.12, how to avoid getting an action?

I have an action method that only triggers when post data to it.
So I add some logic code to prevent the get request.
public function myAction()
{
if($_SERVER['REQUEST_METHOD'] == "GET")
{
echo "No get!";
die();
}
else
{
//some other codes
}
}
It works.
But I have to write these code snippet to many action method. It looks so redundant.
So, is there a better way to implement it like the above code?
Add this method to your controller
public function preDispatch(){
if(!$this->_request->isPost() and in_array($this->_request->getParam('action'), array('action1', 'action2'))){
exit('only post');
}
}
Its too late to answer this question now but hope it will help someone else.
If you want to do this for just one controller then your better off using the controllers _init() method as shown below.
public function _init() {
if(!$this->getRequest()->isPost()){
//The request is not post. Do what you like.
}
}
If you want the same thing for multiple controllers you can create a frontController plugin like this.
class Application_Plugin_Request extends Zend_Controller_Plugin_Abstract {
public function preDispatch(Zend_Controller_Request_Abstract $request){
if(!$request->$isPost()){
//The request is not post. Do what you like.
}
}
}
Add this method to your Bootstrap class for activate the plugin.
protected function _initPlugins(){
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new Application_Plugin_Request(), 17);
}

How to pass errors from model to controller in zend framework

I am using zend framework and this is the skeleton of my model and controller methods
Model Class methods :
_validateRegisterForm($postData)
{
//validating data using Zend_Filter_Input
//Returns instance of Zend_Filter_Input
}
//Return true/false
protected _isNumberAlreadyExists()
{
// I dnt want to perform above validation using zend_validate_db_recordexists
//since i dnt want to mix my dblogic with in buisness logic
}
register($postData)
{
$input=$this->_validateRegisterForm($postData);
if(!$input->isValid())
{
//What should it return to controller
}
if(!$this->_isNumberAlreadyExists($input->number))
{
//What should it return to controller
}
}
controller class api
$this->_model->register($postData)
I want given below condition to return error in same format to controller class
if(!$input->isValid())
{
//What should it return to controller
}
if(!$this->_isNumberAlreadyExists($input->number))
{
//What should it return to controller
}
I can simply return false from model class but for that i have to save zend_filter_Input instance or error message(if number already exists).Thus in that case i have to create another error handler object which can convert error messages into common format and let controller to fetch those error
To me it does not look like a proper way of doing things in zend framework.
Would somoneone like to help me about passing error from model to controller in zend framework or suggest some other method to handle errors in zend framework
Two notes before we start:
First of all, the Model is not a class, but a Layer.
The code below is not ZF specific
To solve your problem you can do
public function register()
{
$this->assertThis($postData);
$this->assertThat($postData);
// do something with $postData
}
The methods assertThis and assertThat are your validation methods, just that instead of returning something, they will throw an appropriate Exception. Since register is a Command, it should not return anything at all.
In your controller, you simply catch the Exceptions and convert them into a format usable by your Presentation Layer (which is what C+V are)
public function registerAction()
{
try {
$this->foo->register($this->getRequest()->whatever());
} catch (ThisException $e) {
// handle here
} catch (ThatException $e) {
// handle here
}
}
Another option would be to collect any errors inside the object doing the registration. You'd then have to return of course and provide a method on that object to get the errors. So it adds cruft to your objects.
public function register()
{
if ($something === false) {
$this->errors = 'Something was false';
return false;
}
// do something with $postData
}
Your controller would then do
public function registerAction()
{
if (false === $this->foo->register($this->whatever())) {
$errors = $this->foo->getErrors();
// do something with $errors
}
}
A third option would be to use a Notification pattern
An object that collects together information about errors and other information in the domain layer and communicates it to the presentation.
See http://martinfowler.com/eaaDev/Notification.html for an in-depth explanation.

Creating a custom codeigniter validation rule

I have a function in my login form that checks if the email and password match the values in the database and if so it logs the user into the system.
I would like to display a validation error if this function returns false.
My problem is that I am unsure how to go about creating this. The message relates to both the password and email fields so I would not want a rule for each input field just display a single message.
I have tried using flashdata to achieve this but it only works when the page has been refreshed.
How can I created a new validation rule solely for the function $this->members_model->validate_member() ??
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_rules('email_address', '"Email address"', 'trim|required|valid_email');
$this->form_validation->set_rules('password', '"Password"', 'trim|required');
if ($this->form_validation->run() == FALSE)
{
$viewdata['main_content'] = 'members/login';
$this->load->view('includes/template', $viewdata);
}
else
{
if($this->members_model->validate_member())
{
You use the callback_ in your rules, see callbacks, for ex.
$this->form_validation->set_rules('email_address', '"Email address"', 'trim|required|valid_email|callback_validate_member');
and add the method in the controller. This method needs to return either TRUE or FALSE
function validate_member($str)
{
$field_value = $str; //this is redundant, but it's to show you how
//the content of the fields gets automatically passed to the method
if($this->members_model->validate_member($field_value))
{
return TRUE;
}
else
{
return FALSE;
}
}
You then need to create a corresponding error in case the validation fails
$this->form_validation->set_message('validate_member','Member is not valid!');
One best way to achieve this is extending CodeIgniter’s Form Validation library. Let say we want to create a custom validator named access_code_unique for the field access_code of the database table users.
All you have to do is creating a Class file named MY_Form_validation.php in application/libraries directory. The method should always return TRUE OR FALSE
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
protected $CI;
public function __construct() {
parent::__construct();
// reference to the CodeIgniter super object
$this->CI =& get_instance();
}
public function access_code_unique($access_code, $table_name) {
$this->CI->form_validation->set_message('access_code_unique', $this->CI->lang->line('access_code_invalid'));
$where = array (
'access_code' => $access_code
);
$query = $this->CI->db->limit(1)->get_where($table_name, $where);
return $query->num_rows() === 0;
}
}
Now you can easily add your new created rule
$this->form_validation->set_rules('access_code', $this->lang->line('access_code'), 'trim|xss_clean|access_code_unique[users]');

Categories