I have tried almost everything in my knowledge and found on net but nothing works. What I am trying to do is while adding new record I want to check whether the field value is already in database table or not. If not than add else throw error message.
I have tried also with is_usnique but than it is not allowing to modify data since it is considering that form value is exists.
Table name is positions
Coloumn name is position
Input field name is position
I have tried below code in my Controller
public function _unique_poscode()
{
$id = $this->uri->segment(4);
$this->db->where('position', $this->input->post('position'));
!$id || $this->db->where('id !=', $id);
$poses = $this->positions_model->get();
if (count($poses)) {
$this->form_validation->set_message('_unique_poscode', '%s should be uinique');
return FALSE;
}
return TRUE;
}
And set rules in my Model as below
public $rules = array(
'position' => array(
'field' => 'position',
'label' => 'Position Code',
'rules' => 'trim|required|max_length[10]|callback__unique_poscode|xss_clean'
),
'label' => array(
'field' => 'label',
'label' => 'Position Label',
'rules' => 'trim|required|max_length[50]|xss_clean'
),
);
but no matter whatever I do it is not working and adding record even if it is exists in table.
Can anyone help me to fix this issue? Thanks a lot.
you are missing parameter
public function _unique_poscode( $p )
{
$this->form_validation->set_message('_unique_poscode', '%s should be uinique');
$q = $this->db->get_where('positions', array('position' => $p));
return ($q->num_rows() > 0) ? TRUE : FALSE;
}
and in rules
...|callback__unique_poscode|trim
and how it is done by codeigniter is as one of rules, please see this for more
is_unique[table.column]
Simply add this to rules and check.
is_unique[TABLENAME.COLUMNNAME]
According to your one it should be,
is_unique[positions.position]
Related
how can we check firstname and last name is unique validation in cakePHP ?
record1:
first name :raj
last name: kumar
if we enter same name in input field , it should show validation message "Record alredy Exists".
i know how to validate single field validation.
how to validate that the combination of first_name and last_name is unique?
Please help me in this.
Thanks in Advance
You will want to setup a custom validation rule for testing that the 'full name' is unique. For example, in your model add a new method for validation like this:-
public function validateUniqueFullName(array $data) {
$conditions = array(
'first_name' => $this->data[$this->alias]['first_name'],
'last_name' => $this->data[$this->alias]['last_name']
);
if (!empty($this->id)) {
// Make sure we exclude the current record.
$conditions[$this->alias . '.' . $this->primaryKey . ' !='] = $this->id;
}
return $this->find('count', array('conditions' => $conditions)) === 0;
}
Then add the new validation rule to the model's $validate property:-
public $validate = array(
'first_name' => array(
'unique' => array(
'rule' => 'validateUniqueFullName',
'message' => 'Not unique'
)
)
);
Where 'rule' => 'validateUniqueFullName' instructs Cake to use the new validation rule to check that the name is unique.
You'll probably want to tweak/improve the above custom rule to meet your exact requirements but it should put you on the right track.
Try this way
public $validate = array(
'facebook_link' => array(
'rule' => array('customValidation','facebook_link'),
'message' => 'Please enter facebook link.'
),
'twitter_link' => array(
'rule' => array('customValidation','twitter_link'),
'message' => 'Please enter twitter link.'
)
);
function customValidation($data , $filed) {
if(empty($data[$filed])) {
return false;
}
return true;
}
I'm new to CakePHP and I'm still learning the basics, through working in a live project and taking help from the CakePHP documentations when necessary. Currently, I'm having the following problem : I've recently changed my database table name and structure, so I was forced to change my view, controller and model names. After changing names, whenever I run the index.ctp page, I get the following error:
Fatal error: Call to undefined method stdClass::read() in C:\wamp\www\sdb\app\controllers
\home_loan_distributions_details_controller.php on line 32
Previously, my view folder was named home_loan_distributions, now it's renamed to home_loan_distributions_details.
My previous controller name was home_loan_distributions_controller.php and current name is home_loan_distributions_details_controller.php. The codes:
class HomeLoanDistributionsDetailsController extends AppController {
var $name = 'HomeLoanDistributionsDetails';
function index() {
$user = $this->Session->read('User');
$user_role = $user['User']['user_role_id'];
$actions = $this->Session->read('actions');
$display_actions = array();
foreach ($actions as $action) {
array_push($display_actions, $action['pm_controller_actions']['name']);
}
$this->set('display_actions', $display_actions);
$this->set('user_role', $user_role);
$branch_id = 18;
$this->set('branch_id', $branch_id);
$conditions = array('branch_id' => $branch_id);
$this->set('HomeLoanDistributionsDetails', $this->paginate($conditions));
$this->HomeLoanDistributionDetail->Branch->recursive = 0;
$this->set('BranchDetailInformation', $this->HomeLoanDistributionDetail->Branch->read(array('Branch.id', 'Branch.name', 'RegionalOffice.name', 'DistrictOffice.name', 'SubDistrictOffice.name', 'ClusterOffice.name'), $branch_id));
}
My model was previously named home_loan_distribution.php and now it's named home_loan_distribution_detail.php. The codes:
class HomeLoanDistributionDetail extends AppModel {
var $name = 'HomeLoanDistributionDetail';
var $actsAs = array('Logable' => array(
'userModel' => 'User',
'userKey' => 'user_id',
'change' => 'list', // options are 'list' or 'full'
'description_ids' => TRUE // options are TRUE or FALSE
));
var $validate = array(
'entry_date' => array(
'rule' => 'date',
'message' => 'Enter a valid date',
'allowEmpty' => true
),
'branch_id' => array('numeric'),
'customer_id' => array('numeric'),
'loan_amount' => array('numeric'),
'service_charge' => array('numeric'),
'security' => array('numeric'),
'loan_taken_term' => array('numeric'),
'purpose_id' => array('numeric'),
'installment_amount' => array('numeric'),
'installment_service_charge' => array('numeric'),
);
//The Associations below have been created with all possible keys, those that are not needed can be removed
var $belongsTo = array(
'Branch' => array(
'className' => 'Branch',
'foreignKey' => 'branch_id',
'conditions' => '',
'fields' => 'id,name',
'order' => ''
)
);
function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()) {
$recursive = 0;
$group = $fields = array('branch_id', 'entry_date');
$order = array('entry_date DESC');
$limit = 4;
$this->paginateCount($conditions);
return $this->find('all', compact('conditions', 'fields', 'order', 'limit', 'recursive', 'group'));
}
function paginateCount($conditions = null, $recursive = 0, $extra = array()) {
$recursive = 0;
$group = $fields = array('branch_id', 'entry_date');
$order = array('entry_date DESC');
$results = $this->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive', 'group'));
return count($results);
}
}
What my guess is: probably I messed up the naming conventions while renaming everything. The problem is definitely within this line in the controller:
$this->set('BranchDetailInformation',
$this->HomeLoanDistributionDetail->Branch->read(array('Branch.id', 'Branch.name',
'RegionalOffice.name', 'DistrictOffice.name', 'SubDistrictOffice.name', 'ClusterOffice.name'),
$branch_id));
Whenever I comment out this line, I stop getting the above mentioned error message and my view page loads (although that still have some data missing - because I need those Branch related data to be displayed in my view.)
I can't figure out what exactly my problem is, but at least I know where it is. I need someone to pinpoint it.
My CakePHP version is 1.2.5, PHP version - 5.2
There is no function read for model.If you want to find some model data then try with -
$this->set('BranchDetailInformation', $this->HomeLoanDistributionDetail->Branch->find('all', $consitions);
$conditions will be the array of all requirements you want to provide. See the docs for more info.
Apparently, the problem seemed to be related to my 'className' => 'Branch' element of the Branch array used in my model, since the stdClass::read() method is related to classes and not models. But I discovered that the problem was elsewhere. This error was part of that problem, but it itself is not the actual problem.
I figured out this morning that my Model name is HomeLoanDistributionDetail, but my table name is home_loan_distributions_details (because someone else has changed the table name). CakePHP convention requires corresponding table name to be plural and model class name to be singular and CamelCased.
Quoting from the CakePHP Cookbook:
Model class names are singular and CamelCased. Person, BigPerson, and ReallyBigPerson are all examples of conventional model names.
Table names corresponding to CakePHP models are plural and underscored. The underlying tables for the above mentioned models would be people, big_people, and really_big_people, respectively.
Considering the above convention, I just had to rename my model class name from HomeLoanDistributionDetail to HomeLoanDistributionsDetail, in order to match with the table name home_loan_distributions_details. Also, I had to change the model file name from home_loan_distribution_detail.php to home_loan_distributions_detail.php.
After doing that, I stopped getting the error and I was successful in retrieving data from table and viewing it.
I am trying to set a field as reuired only when another field selected value not equal to 11.
I have tried this example
array('role', 'ext.YiiConditionalValidator',
'if' => array(
array('role', 'compare', 'compareValue'=>"11"),
),
'then' => array(
array('company_id', 'required'),
),
),
),
I tried downloading new ConditionalValidator.
And even tried custom condition:
public function checkEndDate($attributes,$params)
{
$this->addError('company_id','Error Message');
}
public function rules() {
return array(
array('company_id', 'checkEndDate')
);
}
But it all shows error. Any simple way to solve this?.
Why not using scenarios? If you're creating/editing model with 'customer_type=active' you can before hand create it with special scenario:
$model = new MyModel(MyModel::SCENARIO_ACTIVE);
and then define your rules including scenario:
array('birthdate, city', 'required', 'on' => MyModel::SCENARIO_ACTIVE),
array('city', 'in', 'range' => array("sao_paulo", "sumare", "jacarezinho"), 'on' => MyModel::SCENARIO_ACTIVE)
If you don't like this way, you can always very simply create your own validator.
In rules:
array('customer_type', 'myCustomValidator'),
In the model class:
function myCustomValidator(){
if($this->customer_type == 'active'){
...
if($error){
$this->addError(...);
}
}
}
i am trying to check if an id in the database already exists and if it does not then only insert that id and not the other ones that exist
I have tried to do a where statement that checks if their is a id exists in the database but even if their are new information it does not insert it into the database
Im quite lost here
any guidance would be appreciated
ps i dont want to update a row i want to insert a new updated one that does not exist
$this->db->where('id',$id);
$q = $this->db->get('testing');
if($q)
{
//Do nothing
}
else
{
$this->db->set('id', $id);
$this->db->set('message', $message);
$query= $this->db->insert('testing');
}
Model
<?php
class Fruits_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}
function check()
{
$query = null; //emptying in case
$id = $_POST['id']; //getting from post value
$name = $_POST['name'];
$query = $this->db->get_where('fruits', array(//making selection
'id' => $id
));
$count = $query->num_rows(); //counting result from query
if ($count === 0) {
$data = array(
'name' => $name,
'id' => $id
);
$this->db->insert('fruits', $data);
}
}
}
?>
You have a logic issue with your code that you need to fix.
In your code, you save the result from your query as $q = $this->db->get('testing'),
and $q will always evaluate to true regardless of the number of rows your return.
You need to check the number of rows using $query->num_rows() > 0 and then the rest
of you code will behave as you expect.
For more details, see: http://ellislab.com/codeigniter/user-guide/database/results.html
$ql = $this->db->select('id')->from('testing')->where('id',$id)->get();
if( $ql->num_rows() > 0 ) {} else {
$a = array('id' => $id, 'message' => $message);
$this->db->insert('testing', $a);
}
This should do it.
You should try like this:
public function record_exists(){
$exists = $this->db->get_where('table_name', array('id' => $id));
if($exists->num_rows() > 0 ){
echo "Some message";
return false;
}else{
// Insert your data into the database...
}
}
You need to select the id's in your MYSQL table with the id you want to check and then count the rows. If the row count is 0 then the id doesn't exist.
$query = mysql_query("SELECT * FROM your_table WHERE id='$id'");
$count = mysql_num_rows($query);
If($count!=0){
// id exists
} else {
// id doesn't exist
}
normally 'id' field is set with auto_increment and set primary which is unique and not repeatable. So there is not problem to worry about existing.
However, in your case I think you are not using it as a 'unique field'.
Let me give you an example.
Here I have a table name 'fruits'
++++++++++++++++++++++++++++++++++++
ငfruit_id | int (primary)
name | text
id | int
++++++++++++++++++++++++++++++++++++++
in your model
function checkId($id)
{
$query=$this->db->get_where('fruits',array('id'=>$id)); //check if 'id' field is existed or not
if($query!=null) // id found stop
{
return FALSE;
}
else // id not found continue..
{
$data = array(
'fruit_id' => $fruit_id ,
'name' => $name ,
'id' => $id
);
$this->db->insert('fruits', $data);
}
}
For Checking An Id Or any column value exist not in database CI have a validation rule for it.
See it live here: Validation Rule
Rule: is_unique
Returns FALSE if the form element is not unique to the table and field name in the parameter. Note: This rule requires Query Builder to be enabled in order to work.
Example: is_unique[table.field]
$this->form_validation->set_rules(
'username', 'Username',
'required|min_length[5]|max_length[12]|is_unique[users.username]',
array(
'required' => 'You have not provided %s.',
'is_unique' => 'This %s already exists.'
)
);
For More Advance use of validation, You can add all validation Setting Rules Using an Array.
$this->form_validation->set_rules(
'username', 'Username',
'required|min_length[5]|max_length[12]|is_unique[users.username]',
array(
'required' => 'You have not provided %s.',
'is_unique' => 'This %s already exists.'
)
);
$config = array(
'your_rule_name' => array(
array(
'username', 'Username',
'required|min_length[5]|max_length[12]|is_unique[users.username]',
array(
'required' => 'You have not provided %s.',
'is_unique' => 'This %s already exists.'
)
)
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required'
)
);
$this->form_validation->set_rules($config);
Let's start this off with a short code snippet I will use to demonstrate my opinion:
$title = new Zend_Form_Element_Text('title', array(
'label' => 'Title',
'required' => false,
'filters' => array(
'StringTrim',
'HtmlEntities'
),
'validators' => array(
array('StringLength', false, array(3, 100))
),
));
This important line is:
'required' => false,
Which means that the input field is not required and you can submit the form without filling it. However, this also means that any filters and validators won't apply to it if you choose to fill in this field.
Common sense tells me that is an irrational behavior. The way I understand the word 'required' in relation with HTML input fields: an input field that is not required should return NULL if it is not filled in but if user decides to fill it both filters and validators should apply to it. That's what makes sense to me. Do you agree with me or is my common sense not so common?
Now more practical question, because this is how Zend_Form behaves, how can I achieve not required fields which would work as I described above (if nothing is typed in by user it returns NULL otherwise filters and validators normally apply).
Not really a complete answer to your question, but since comments don't have syntax formatting; here's a filter you can use to make your field values null if empty.
class My_Filter_NullIfEmpty implements Zend_Filter_Interface
{
public function filter( $value )
{
// maybe you need to expand the conditions here
if( 0 == strlen( $value ) )
{
return null;
}
return $value;
}
}
About the required part:
I'm not sure really. You could try to search the ZF mailinglists on Nabble:
http://www.nabble.com/Zend-Framework-Community-f16154.html
Or subscribe to their mailinglist, and ask them the question. Either through Nabble, or directly via the addresses on framework.zend.com:
http://tinyurl.com/y4f9lz
Edit:
Ok, so now I've done some tests myself, cause what you said all sounded counter intuitive to me. Your example works fine with me. This is what I've used:
<?php
class Form extends Zend_Form
{
public function init()
{
$title = new Zend_Form_Element_Text('title', array(
'label' => 'Title',
'required' => false,
'filters' => array(
'StringTrim',
'HtmlEntities',
'NullIfEmpty' // be sure this one is available
),
'validators' => array(
array('StringLength', false, array(3, 100))
),
));
$this->addElement( $title );
}
}
$form = new Form();
$postValues = array( 'title' => '' ); // or
$postValues = array( 'title' => ' ' ); // or
$postValues = array( 'title' => 'ab' ); // or
$postValues = array( 'title' => ' ab ' ); // or
$postValues = array( 'title' => '<abc>' ); // all work perfectly fine with me
// validate the form (which automatically sets the values in the form object)
if( $form->isValid( $postValues ) )
{
// retrieve the relevant value
var_dump( $form->getValue( 'title' ) );
}
else
{
echo 'form invalid';
}
?>
Actually, what you describe as your expectations are exactly how Zend_Form works. If you mark the element as not required, then the following happens: (a) if no value is passed, it skips validation, but if (b) a value is passed, then it must pass all validators in order to be valid.
BTW, best place to ask ZF questions is on the ZF mailing lists: http://framework.zend.com/archives