I have select input in my form for manufacturers.
<div class="form-group">
<label for="manufacturer">Manufacturer</label>
<select id="manufacturerSelect" name="manufacturer" class="form-control">
<option disabled selected value> -- select an manufacturer -- </option>
<?php foreach ($manufacturers as $manufacturers_item): ?>
<option value="<?=$manufacturers_item['id'];?>" <?php echo set_select('manufacturer',$manufacturers_item['id'], ( !empty($manufacturer) && $manufacturer == $manufacturers_item['id'] ? TRUE : FALSE )); ?> ><?=$manufacturers_item['name'];?></option>
<?php endforeach; ?>
<option disabled>──────────</option>
<option value="24" <?php echo set_select('manufacturer','24', ( !empty($manufacturer) && $manufacturer == '24' ? TRUE : FALSE )); ?> >Other</option>
</select>
<?php echo form_error('manufacturer'); ?><br />
</div>
If "other" (value == 24) is checked additional input is asked:
$('body').on('change', '#manufacturerSelect', function() {
if ($(this).val() == 24) {
$("#otherManufacturerSelect").removeClass('hidden');
} else {
$("#otherManufacturerSelect").addClass('hidden')
}
});
And HTML:
<div id="otherManufacturerSelect" class="form-group">
<label for="otherManufacturer" >What is it then?</label>
<input type="text" name="otherManufacturer" class="form-control">
<?php echo form_error('otherManufacturer'); ?><br />
</div>
CSS:
.hidden {
display: hidden;
}
Now if user picks "other" as manufacturer addition input is displayed. Form validation rule for otherManufacturer is added in server side if manufacturer == 24. The problem is that the other manufacturer input is displayed every time user get response from server. I could add class="hidden" by default to other manufacturer div but if the form validation doesnt run other manufacturer field will not be displayed again to user.
What I need is PHP IF condition inside:
<div id="otherManufacturerSelect" <?php if(/*???*/):?>class="hidden"<?php endif; ?> class="form-group">
So that class="hidden" would be added only if manufacturer is not "other". but I cannt think of rigth condition.
Any help would be appreciated!
EDIT
Controller:
public function create()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('manufacturer', 'Manufacturer', 'required');
if($this->input->post('manufacturer') == '24'){
$this->form_validation->set_rules('otherManufacturer', 'Other manufacturer', 'required');
}
$data['manufacturers'] = $this->puzzles_model->getManufacturers();
if ($this->form_validation->run() === FALSE)
{
$this->load->view('puzzles/create', $data);
}
else
{
/* do the upload, return upload errors or save in db*/
}
}
In your particular case this would fix the problem:
<div id="otherManufacturerSelect" class="form-group <?php if(isset($manufacturer) && $manufacturer !== '24') { echo 'hidden'; } ?> ">
<label for="otherManufacturer" >What is it then?</label>
<input type="text" name="otherManufacturer" class="form-control">
<?php echo form_error('otherManufacturer'); ?><br />
</div>
Then you can remove the JS snippet. The additional form will be hidden on server side (class="hidden" will be set).
I saw that you're using var $manufacturer in the same template. I can't see your controller and how you're passing variables but instead of $manufacturer you can also use $_GET['manufacturer'] or $_POST['manufacturer'] (depending on your form action method).
Notice: $_GET['manufacturer'], $_POST['manufacturer'] and $_REQUEST['manufacturer'] is NOT sanitized input. When using $manufacturer I assume that it's sanitized in your controller.
Related
I need a help for avoid duplication entries on my database table using CodeIgniter.
I have a table called “user_course_tbl” with 3 columns as mentioned below.
Id
staff_name
course_code
I need to enter staff name and course code without duplications.
As mentioned in table, same person can add more different course codes. But same person couldn’t add same course code more than 1.
Ex: Smith has more different courses for the table. It will be ok. But Ann has same course more than 1. This should be avoiding. should not have same value for staff_name and course_code columns both together.
I wrote coding for the above matter. But I couldn’t understand to validate this matter.
View
<?php echo form_open_multipart('Course/insert_courses_for_users');?>
<div class="box-body">
<div class="col-md-6">
<div class="form-group">
<label>User</label>
<select id="user" class="form-control" name="user" required>
<option value="">Select</option>
<?php
if(isset($user))
{
foreach($user as $cnt)
{
print "<option value='".$cnt['staff_name']."'>".$cnt['staff_name']."</option>";
}
}
?>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Course Code</label>
<select id="CourseCode" class="form-control" name="courscode" onchange="getcoursename(this.value)" required>
<option value="">Select</option>
<?php
if(isset($coursecode))
{
foreach($coursecode as $cnt)
{
print "<option value='".$cnt['course_code']."'>".$cnt['course_code']."</option>";
}
}
?>
</select>
</div>
</div>
Controller
function insert_courses_for_users()
{
$this->form_validation->set_rules('user', 'User', 'required');
$this->form_validation->set_rules('courscode', 'Course Code', 'required');
$id=$this->input->post('txtid');
$user=$this->input->post('user');
$coursecode=$this->input->post('courscode');
$data=$this->Course_model->insert_courses_for_user(array('id'=>$id,'staff_name'=>$user,'course_code'=>$coursecode));
if($data==true)
{
$this->session->set_flashdata('success', "New Course added for user Succesfully");
}else
{
$this->session->set_flashdata('error', "Sorry, New Course added for user is Failed.");
}
redirect($_SERVER['HTTP_REFERER']);
}
Model
function insert_courses_for_user($data)
{
$this->db->insert("user_course_tbl",$data);
return $this->db->insert_id();
}
Could you please help to solve this matter?
(1)Method:-
In Controller:-
When you define the form validation , add a validator for is_unique
$this->form_validation->set_rules('staff_name', 'Staff Name', 'required|is_unique[user_course_tbl.staff_name]');
(2)Method:-
Search in the database ,the course_code & staff_name before insertion they exsists or not.
Solution 1
$courscode=$this->db->query('select * from user_course_tbl where
courscode='.$this->input->post('courscode'));
if(isset($courscode) && !empty($courscode)) { $is_unique =
'|is_unique[user_course_tbl.courscode]' } else { $is_unique = ''
}
$this->form_validation->set_rules('courscode', 'Course Code',
'required|trim|xs0s_clean'.$is_unique);
$this->form_validation->set_message('is_unique', 'The %s is already
taken, Please use another %s'); // add message for the is_unique
note :use same for staff name.
Solution 2:
$this->form_validation->set_rules('courscode', 'Source Code', 'required|is_unique[user_course_tbl.courscode');
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.
I want delete user and user role by using checkbox. first check then submit button click. After click, selected user and user_role should be deleted.
got php undefined offset 2 error on line 491
this is my model:
public function add_participation(){
$user = $this->input->post('user');
$role = $this->input->post('role');
$delete = $this->input->post('delete');
for($i=0;$i<count($user);$i++){
if($user[$i] !=""){
$this->db->where('workflow_activity_id',$this->input->post('batch'));
$this->db->where('role_id',$role[$i]);
$this->db->where('user_id',$user[$i]);
$exist = $this->db->get('workflow_participation');
$data = array(
'user_id' => $user[$i],
'role_id' => $role[$i],
'workflow_activity_id' => $this->input->post('batch'),
);
if($exist->num_rows() == 0){
$this->db->insert('workflow_participation',$data);
}else{
$this->db->where('workflow_activity_id',$this->input->post('batch'));
$this->db->where('role_id',$role[$i]);
$this->db->where('user_id',$user[$i]);
$this->db->update('workflow_participation',$data);
}
if($delete[$i] == '1'){ //**error on this line**
$this->db->where('workflow_activity_id',$this->input->post('batch'));
$this->db->where('role_id',$role[$i]);
$this->db->where('user_id',$user[$i]);
$this->db->delete('workflow_participation');
}
}
}
return true;
}
In this view page user and user_role show in drop-down.
This is my view page
<div class="form-group">
<label class="control-label col-md-3">User :</label>
<div class="col-md-8">
<select id="user" name="user[]" class="select form-control">
<option value="" selected="selected">-------</option>
<?php
if(!empty($user)){
foreach($user as $user_result){?>
<option value="<?=$user_result->id;?>" <?php if(!empty($participent) && !empty($participent[1]) && $participent[1]->user_id == $user_result->id){?>selected="selected"<?php }?>><?=$user_result->username;?></option>
<?php }}?>
</select>
</div>
<label class="control-label col-md-3">Role :</label>
<div class="col-md-8">
<select id="role" name="role[]" class="select form-control">
<option value="" selected="selected">-------</option>
<?php
if(!empty($role)){
foreach($role as $role_result){?>
<option value="<?=$role_result->id;?>" <?php if(!empty($participent) && !empty($participent[1]) && $participent[1]->role_id == $role_result->id){?>selected="selected"<?php }?>><?=$role_result->name;?></option>
<?php }}?>
</select>
</div>
<label class="control-label col-md-3">Delete :</label>
<div class="col-md-8">
<input type="checkbox" name="delete[]" value="1">
</div>
Since you are using delete[] as array, i hope your view is in a loop.
a checkbox value is submitted only when it is checked. So you will receive your input in wrong order.
ie, you selected first user and role and checked last delete, you may receive delete for first user. The second and third delete will be undefined. Please see this link for details and hidden field hack for this issue
So I suggest change the following 3 lines in your html as following. you can use $participent[1]->user_id ( or a counter) as index in view file.
<select id="user" name="user[<?php echo $participent[1]->user_id;?>]" class="select form-control">
...
<select id="role" name="role[<?php echo $participent[1]->user_id;?>]" class="select form-control">
...
<input type="checkbox" name="delete[<?php echo $participent[1]->user_id;?>]" value="1">
change the loop from this
for($i=0;$i<count($user);$i++){
to
foreach( $user as $i => $unused ) {
Then instead of equal checking
if($delete[$i] == '1'){ //**error on this line**
use
if( isset($delete[$i]) ){ //**error on this line**
// if( $delete[$i] == '1' ){ //uncomment if you need double confirmation
First check if the variable $role have the same amount of data as $user, if it's not so you have a problem.
Next for the line for($i=0;$i<count($user);$i++), create an outside variable for your count, here everytime you enter the for, the count() is called, bad optimisation.
My code snippet:
<div class="col-sm-2">
<label>Weight</label>
<?php for($i=0;$i<4;$i++){ ?>
<input type="text" placeholder="Weight" name="weight[]" id="weight_<?php echo $i; ?>" class="form-control weight_cls" />
<?php } ?>
<div class="err"><?php echo form_error('weight[]'); ?></div>
</div>
If i use following CI validation:
$this -> form_validation -> set_rules('weight[]', 'Weight', 'required|numeric');
Then it will not allow until fill all fields..
I want to allow at least one.. how can i??
Create your own validation method :
$this->form_validation->set_rules('weight[]', 'Weight', 'callback_weight_check');
And in the same controller :
public function weight_check($weight)
{
if(count(array_filter($weight)) == 0) {
$this->form_validation->set_message('weight_check', 'Fill at least one value');
return false;
}
return true;
}
More infos : https://www.codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods
Get the input form form
$weight = $this->input->post('weight'); //or get as your form
$weight is an array so you can use foreach loop to validate each element as below:
foreach($weight as $key=>$val)
{
$this->form_validation->set_rules("weight[".$key."]", "weight", 'required|numeric');
// you can have one more row as per your requirement.
}
I created a drop-down to select the category for search. When I search the product for example I search Shoes for MEN, when the view page loaded the item resets to default
I want the category to remain what I selected
<form action="<?php echo Yii::app()->baseUrl; ?>/search" method="GET" class="form-inline form-section-2 row fadeInDown animated">
<div class="col-sm-5 form-group">
<input type="text" name="loc" class="form-control" id="loc" value="<?php echo $locationdet ; ?>" placeholder="Enter Your Keyword">
</div>
<div class="col-sm-4 form-group" >
<select name="cat" class="form-control selectpicker">
<option>Select Category</option>
<option value = '0'>Men</option>
<option value = '1'>Women</option>
</select>
</div>
<div class="col-sm-3 form-group">
<button type="submit" class="btn btn-default btn-new">Search Products</button>
</div>
</form>
Try this:
<option value = '0' <?php if(isset($_GET['cat']) && $_GET['cat'] == '0') echo "selected" ?>>Men</option>
<option value = '1' <?php if(isset($_GET['cat']) && $_GET['cat'] == '1') echo "selected" ?>>Women</option>
use
echo CHtml::dropDownList('cat',isset( $_REQUEST['cat'] ) ? $_REQUEST['cat'] : NULL, array('0'=>'Men', '1'=>'Women'),
array('empty'=>'Select Category', 'class' => 'form-control selectpicker'));
to achieve yii style,
cheers
You will have to pass the selected option via the controller back to the view.
In the controller you will need something like this:
$this->render('viewName', array('name' => 'valueOfTheList'))
Then in the view you can use
<option value = '0' <?php if($name == '0') echo "selected" ?>>Men</option>
<option value = '1' <?php if($name == '1') echo "selected" ?>>Women</option>
However. Since you are using Yii. I would advise you to look at CHTML::dropDownList(). Then you could do something like
<?php echo CHtml::dropDownList('name', $select,
array('M' => 'Male', 'F' => 'Female'));
Which is really a more Yii way to approach these kind of things.
Yii way to implement this functionality.
You can keep the form state by setting the user input value to Model properties. For this, you can use CFormModel to implement, same like YII's default login page. Below is a sample example.
Create a form model for your search (SearchForm.php) and place this inside models folder.
class SearchForm extends CFormModel
{
public $search_key;
public $search_cat;
public function rules()
{
return array(
array('search_key,search_cat', 'required'),
);
}
}
Assume i am using SiteController. I want to show this search form in my index page. When i submit the form it will submitted to search action
class SiteController extends Controller
{
public function actionIndex()
{
$searchModel=new SearchForm();
$searchModel->search_key;
$searchModel->search_cat;
$this->render('index',array('searchModel'=>$searchModel));
}
public function actionSearch()
{
$searchModel=new SearchForm();
if($_POST['SearchForm'])
{
$searchModel->attributes=$_POST['SearchForm'];
}
$this->render('search',array('searchModel'=>$searchModel));
}
}
$searchModel->attributes=$_POST['SearchForm']; That is i am resetting the user inputs to model.So, in your view the form will appear with user input values.
Call this Form in views
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'search-form',
'enableClientValidation' => true,
'action'=>array('default/search'), //Submiting my form to Search action
));
?>
<?php echo $form->textField($searchModel, 'search_key'); ?>
<?php
$htmlOptions = array('size' => '1', 'prompt' => 'Select');
$list = array('0' => 'Men', '1' => 'Women'); // You can load your Categories from the Database table/Model.
echo $form->dropDownList($searchModel, 'search_cat', $list, $htmlOptions);
?>
<?php echo CHtml::submitButton('Search'); ?>
<?php $this->endWidget(); ?>
Hope, This will help you for your better practice.