How to validate associated models in cakephp - php

Hello Could please tell me.
How to validate associated models in cakephp?
i am using multiple model in one controller and controller name is 'AdminsController'.
These are Model in AdminsController
$uses=array('index','Static_page_view','Admin','Categories','Products', 'contact','User','Rams');'
now i want to validate 'Categories'(Model). i have defined set of validation rules. But not ale to validate. While when i use 'Admin'(MODEL) it works perfectly.
<?php
class AdminsController extends AppController {
public $uses=array('index','Static_page_view','Admin','Categories','Products', 'contact','User','Rams');
public function index()
{
if(!empty($this->request->data)) //this checks if the form is being submitted and is not empty
{
if($this->Admin->save($this->request->data))//this saves the data from the form and also return true or false
{
$this->Session->setFlash('The post was successfully added!');
$this->redirect(array('action'=>'index'));
}
else
{
$this->Session->setFlash('The post was not saved, please try again');
}
}
public function Add_Category()
{
if(!empty($this->request->data)) //this checks if the form is being submitted and is not empty
{
if($this->Rams->save($this->request->data))//this saves the data from the form and also return true or false
{
$this->Session->setFlash('The post was successfully added!');
$this->redirect(array('action'=>'Add_Category'));
}
else
{
$this->Session->setFlash('The post was not saved, please try again');
}
}
}
}
\app\Model\Admin
<?php
class Admin extends AppModel {
public $validate = array( ['Admin'] => array(
'name'=>array(
'title_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'Please Enter your Name!'
)
),
'email'=>array(
'body_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'Please Enter your Email!'
)
),
'phone'=>array(
'body_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'Please Enter your phone!'
)
),
'query'=>array(
'body_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'Please Enter your Query!'
)
)
));
}
\app\Model\categories
<?php
class Categories extends AppModel {
public $validate = array(
'name'=>array(
'title_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'Please Enter your Name!'
)
),
'email'=>array(
'body_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'Please Enter your Email!'
)
),
'phone'=>array(
'body_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'Please Enter your phone!'
)
),
'query'=>array(
'body_must_not_be_blank'=>array(
'rule'=>'notEmpty',
'message'=>'Please Enter your Query!'
)
)
);
}
\app\View\admins\index.ctp
<h2>Add a Post</h2>
<?php
echo json_encode($this->validationErrors);
//<!--create the form 2parameter:the post model and the 2nd is the form is submitted to which action-->
echo $this->Form->create('Admin', array('action'=>'index'));
echo $this->Form->input('name');//<!--We have not specified the field so type becomes text as the according to the database field type-->
echo $this->Form->input('email');
echo $this->Form->input('phone');
echo $this->Form->input('query');//<!--We have not specified the field so type becomes textarea as the according to the database field type-->
echo $this->Form->end('Create a Post');//<!--ends the form and create the text on button the same as specified-->
?>
\app\View\admins\category.ctp
<head>
<title>Admin Panel</title>
</head>
<body>
<div id="container">
<?php echo $this->element("header"); ?>
<div id="content">
<?php echo $this->element("left-content"); ?>
<div id="right-content">
<div id="upper">
<h3>Add SubCategory</h3>
</div><!---upper end--->
<?php
echo $this->Form->create('Admin', array('class' => "righform"));
$options = array();
?>
<fieldset class="textbox">
<label class="cate"><span>Main Category :</span>
<select name="parentId">
<?php foreach($name as $row){?>
<option value="<?php echo $row['Categories']['id'];?>"><?php echo $row['Categories']['name']; ?></option>
<?php } ?>
</select>
</label>
<br /><br /><br />
<label class="cate">
<?php echo $this->Form->input('name'); ?>
<br /><br /><br />
<label class="cate1">
<?php echo $this->Form->input('Description'); ?>
<br /><br /><br />
<br /><br /><br />
<td><button class="button" type="submit">Submit</button></td>
</fieldset>
</form>
</div>
</div><!---main content end--->
</div><!----content end---->
<?php echo $this->element("footer"); ?>
</div><!---container end---->
</body>
</html>
Thanks in Advance.

if your model are connected by relationship let say Admin has a OnetoOne/manytomany/onetomany relationship to Category
you can validate it by
$this->Admin->Category->saveAll(array('validate'=> 'only')); // pass 'only' string not only
or if you want to use any model which has no relation to default model then simply first load it on your current controller and then validate it let say category has no relation to current model then simply
$this->loadModel('category');
$this->category->set($this->data);
$this->category->saveAll(array('validate'=> 'only'));
Hope it will help you

you can use Multivalidatable behavior.
http://bakery.cakephp.org/articles/dardosordi/2008/07/29/multivalidatablebehavior-using-many-validation-rulesets-per-model

Related

How to get validation errors in codeigniter?

Hello I am inserting data in database. When I insert both category and description then data in inserting but when I don't insert in the category and description input and click on create then no error showing with blank page admin/category/ register_category, I want to show that category and description field should not be empty.
category.php view page is below :
<?php if(isset($_SESSION['success'])){ ?>
<div class="alert alert-success"><?php echo $_SESSION['success']; ?>
</div>
<?php } ?>
<?php echo validation_errors('<div class="alert alert-danger">','</div>'); ?>
<form class="form" action="<?php echo site_url('admin/category/register_category') ?>" method="POST">
<label for="contactinput5">Category Name</label>
<input class="form-control border-primary" type="text" placeholder="category" name="category" id="contactinput5">
<label for="contactinput5">Discription</label>
<textarea class="form-control border-primary" type="text" placeholder="discription" name="discription" id="contactemail5"></textarea>
<button type="submit" name="create" class="btn btn-primary">
and my controller Category.php page is:
<?php
class Category extends CI_Controller {
function index() {
$this->load->view('admin/category');
}
function register_category() {
$this->form_validation->set_rules('category', 'Category', 'required');
$this->form_validation->set_rules('discription', 'Discription', 'required');
if($this->form_validation->run() == TRUE){
echo "form validate";
$this->load->model('categories');
$insert_category = $this->categories->validate();
if($insert_category){
$this->session->set_flashdata("success","Your data has been added");
redirect("admin/category","refresh");
}
else{
redirect('admin/category');
}
}
}
}
?>
model categories page:
<?php
class Categories extends CI_Model
{
function validate()
{
$arr['categoryname'] = $this->input->post('category');
$arr['discription'] = $this->input->post('discription');
return $this->db->insert('category',$arr);
}
}
?>
If validation result is not true, you can get errors from $this->form_validation->error_array(), loop the return array and show the error to the user.
Hope this help.
hey guys thanks and i got my answer just by putting this code
if($this->form_validation->run() == FALSE)
{
$this->index();
}
Hello Please update your function in the controller. There is issue in validation condition Changes TURE to FALSE. Check below code.
function register_category()
{
$this->form_validation->set_rules('category', 'Category', 'required');
$this->form_validation->set_rules('discription', 'Discription', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('category');
}
else
{
$this->load->model('categories');
$insert_category = $this->categories->validate();
if($insert_category)
{
$this->session->set_flashdata("success","Your data has been added");
redirect("admin/category","refresh");
}
else
{
redirect('admin/category');
}
}
}
Get all post validation errors in controller :
echo validation_errors();
If you want to show at the end of textbox use this following method :
<label for="contactinput5">Category Name</label>
<input class="form-control border-primary" type="text" placeholder="category" name="category" id="contactinput5">
<?php echo form_error('category', '<div class="error">', '</div>'); ?>
FYI your solution only worked because validation_errors() only applies to the current instance. When you redirect that information is lost. You would have to store it in session variable or this is common (change form action to self or leave blank):
function index() {
if ($_POST) {
$this->form_validation->set_rules('category', 'Category', 'required');
$this->form_validation->set_rules('discription', 'Discription', 'required');
if($this->form_validation->run() == TRUE){
$this->load->model('categories');
$insert_category = $this->categories->validate();
if($insert_category){
$this->session->set_flashdata("success","Your data has been added");
}
}
}
$this->load->view('admin/category');
}
Of course your way works too if you are ok with the url changing.

CodeIgniter Validation Not Displaying On Form

Another CI Validation Error here. I've tried searching and from what I can see, the code I have is OK. The validation runs - if I just echo out a "Validation Failed" string from the controller, it displays.
But I cannot seem to get it to display in an actual view. Even if I have a single line in the view (ie echo validation_errors(); ), there are no errors output even though it fails validation.
Any pointers would be greatly appreciated :)
Controller
public function add() {
if ($this->form_validation->run('user_add_edit') == FALSE)
{
//Validation failed
$this->load->view('templates/header_generic');
$this->load->view('templates/navigation');
$this->load->view('user/add_user_form');
$this->load->view('templates/footer_generic');
}
else
{
echo "Form validated!";
}
}
View (Partial)
<div class="panel-body">
<?php echo validation_errors(); ?>
<?php echo form_open('user/add'); ?>
<label for="email">
Email Address
</label><br />
<div class="form-group input-group <?php echo null === form_error('email') || is_null(form_error('email')) ? 'form-group has-error' : ''; ?>">
<span class="input-group-addon">#</span>
<?php echo form_input($email_attr, set_value('email')); ?>
</div>
<br />
<?php echo form_error('email');?>
<br />
<?php echo form_fieldset("Password"); ?>
jfkdjflkdjflks
<?php echo form_fieldset_close(); ?>
<br />
<?php echo form_submit("submit", "Add New User", "class='btn btn-success'"); ?>
</form>
</div>
Form Validation
$config = array(
'user_add_edit' => array(
array(
'field' => 'email',
'label' => 'Email Address',
'rules' => 'trim|required|valid_email|is_unique[user.email]',
'errors' => array(
'required' => 'You must enter a %s',
'valid_email' => '%s is not a valid email address',
'is_unique' => 'This email address already exists'
)
),
Having MY_Form_validation.php improperly set up can mess up with setting of form rules via config file.
Fix
In application/libraries/MY_Form_validation.php - replace your constructor with the below code or just follow the changes below by adding the $config parameter.
function __construct($config = array()){
parent::__construct($config);
$this->CI =& get_instance();
}
It's also a possibility that the value of $config variable is being overwritten that's happening inside application/config/form_validation.php. Check for it as well.
Alternative:
Load the form_validation.php config file from the controller method and pass the relevant config item to set_rules(..) like in the following.
public function add() {
$this->load->config('form_validation');
$this->form_validation->set_rules($this->config->item('user_add_edit'));
if ($this->form_validation->run() == FALSE)
{
//Validation failed
$this->load->view('templates/header_generic');
$this->load->view('templates/navigation');
$this->load->view('user/add_user_form');
$this->load->view('templates/footer_generic');
}
else
{
echo "Form validated!";
}
}

Insert into DB with codeigniter 3

im trying to add new post into my db. I have Model, Controller and View created. Actualy im using rest api for this, but now I want to do it with pure php powerd.
But After form validation is nothing. So when I try to post, nothuing happens.
Here is my code.
Model:
// Create
function create($data) {
// Insert data into DB
$this->db->insert('blog', $data);
return $this->db->insert_id();
}
Controller:
public function add() {
if ($this->ion_auth->is_admin()) {
// Validation rules
$this->form_validation->set_rules('title', 'Titel', 'required');
$this->form_validation->set_rules('teaser', 'Teaser', 'required');
$this->form_validation->set_rules('full', 'Volltext', 'required');
if (($this->form_validation->run() == FALSE)) {
$this->load->view('templates/backend/header', $this->data);
$this->load->view('pages/backend/blog/add', $this->data);
$this->load->view('templates/backend/footer');
} else {
if($this->input->post()) {
$data = array(
'title' => $this->input->post('title'),
'teaser' => $this->input->post('teaser'),
'full' => $this->input->post('full')
);
$this->blog_model->create($data);
redirect(base_url().'blog/');
}
}
} else {
redirect('login');
}
}
And at least my view:
<div class="uk-margin-top">
<?php $attributes = array("class" => "uk-panel uk-panel-box uk-form uk-margin-lage-bottom", "id" => "add-form", "method" => "post");
echo form_open("/backend/blog/add", $attributes); ?>
<div class="uk-form-row">
<label class="uk-form-label" for="title">Title</label>
<input id="title" class="uk-width-1-1 uk-form-large title redactor-box" name="title" placeholder="Beitragstitel" type="text"
value="<?php echo set_value('title'); ?>"/>
<span class="uk-text-danger"><?php echo form_error('title'); ?></span>
</div>
<div class="uk-form-row">
<label class="uk-form-label" for="teaser">Teaser</label>
<textarea id="teaser" class="uk-width-1-1 uk-form-large teaser redactor-box" name="teaser" data-uk-htmleditor></textarea>
<span class="uk-text-danger"><?php echo form_error('teaser'); ?></span>
</div>
<div class="uk-form-row">
<label class="uk-form-label" for="body">Body</label>
<textarea id="full" name="full" rows="4" placeholder="Ihre Nachricht"
value="<?php echo set_value('full'); ?>"></textarea>
<span class="uk-text-danger"><?php echo form_error('full'); ?></span>
</div>
<div class="uk-form-row">
<a class="uk-button uk-button-success" data-action="add-post">Submit</a>
</div>
<?php echo form_close(); ?>
</div>
So my problem is, when I click on my submit button - nothing. Maybe you can show me where my problem is.
Thank you!
For your controller, I think you are missing the form helper and validation library. I have included other comments in the code, but try this:
public function add() {
// you need to load these in:
$this->load->helper('form');
$this->load->library('form_validation');
// I am assuming ion_auth is working, however, I would try this code without
// this conditional statement
if ($this->ion_auth->is_admin()) {
// Validation rules
// Make sure the second parameter is right. I think Titel should be Title.
$this->form_validation->set_rules('title', 'Titel', 'required');
$this->form_validation->set_rules('teaser', 'Teaser', 'required');
$this->form_validation->set_rules('full', 'Volltext', 'required');
// added a triple === instead of == for stricter type checking
if (($this->form_validation->run() === FALSE)) {
// I am assuming $this->data is a property of your controller class
$this->load->view('templates/backend/header', $this->data);
$this->load->view('pages/backend/blog/add', $this->data);
$this->load->view('templates/backend/footer');
} else {
// Check if the form was submitted via $_POST method
if($this->input->post()) {
// I removed your $data array and created it in the model.
// I added a condition here to check if the data was successfully inserted
if ($this->blog_model->create()) {
redirect(base_url().'blog/');
} else {
// output an error message or redirect
}
}
}
} else {
redirect('login');
}
}
For your model, I think you were not passing any data to your model. Try the following for your model:
public function create()
{
// you need to pass an array of data or an object
// the array key corresponds to your db table column
// the array value corresponds to your views input field names
$data = array(
'name' => $this->input->post('title'),
'teaser' => $this->input->post('teaser'),
'full' => $this->input->post('full')
);
// returns true or false
return $this->db->insert('blog', $data);
}

$this->form_validation->run() is return always false in Codeigniter

First of all, i want to know that i am new in Codeigniter. I have a form with one field and submit button And checking validation.But, $this->form_validation->run() is giving false.
Here is my code:
<body>
<h3>Please give a valid website url!!!.</h3>
<?php echo form_open('website/submission'); ?>
<p><input type="text" name="website"></p>
<p><input type="submit" name="submit" value="Check Website"></p>
<?php echo form_close();?>
</body>
And this is my controller:
<?php
defined('BASEPATH') OR exit('u are not here');
class Website extends CI_Controller{
public function __construct(){
parent::__construct();
}
public function index(){
$this->load->view('form');
}
public function submission(){
$formRules=array(
array(
'field'=> 'website' ,
'label'=> 'Website Url',
'rules'=>'required|minlength[3]|maxlength[10]'
)
);
$this->form_validation->set_rules($formRules);
if ($this->form_validation->run() == FALSE)
{
echo 'Failed';
}
else
{
echo 'Success';
}
}
}
Why it is giving always false, even i m typing "minimum 3 and maximum 4" letters in textbox?

How to add a textfield in form and set email validation with out model class in YII?

Hello friend is it possible to create a custom field in form and set email validation.
<?php echo CHtml::textField('references', '', array('size'=>60,'maxlength'=>255)) ?>
I want to allow user to insert only a valid email.
I think the simplest solution - to create a small model:
class EmailModel extends CFormModel {
public $email;
public function rules()
{
return array( array('email', 'email') );
}
}
Only seven strings!
And in view:
$model = new EmailModel();
$form = $this->beginWidget('CActiveForm', array(
'enableClientValidation'=>true
));
echo $form->error($model, 'email');
echo $form->emailField($model, 'email', array ( ));
$this->endWidget();
yes.. you can set jquery script in you view page
<script type="text/javascript">
$("#references").blur(function(){
//here set your email validation
});
});
</script>
Two method mention below through user can enter only valid email
pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$"
Second Method
<input type="email" placeholder="Email Address" class="text" name="email" value="">

Categories