where to add- class="required" (jquery validation) in form_dropdown? - codeigniter

I have a dropdown list which is being populated from database. It is working fine but in the form_dropdown in the view file, I want to add class="required" for validating the dropdown using Jquery. I have tried to make it work but as it turned out it won't work. Would you please kindly help me where exactly to put the class="required" - and make the jquery validation work?
Thanks in Advance
I have this in my controller
// To get the batch name
$this->load->model('dropdown_batchlist');
$data['dropdown_batchlist']= $this->dropdown_batchlist->dropdown_batchlist();
this in my model-
function dropdown_batchlist() {
$this->db->select('batchname, batchid');
$records=$this->db->get('batch');
$data=array();
// add it here as the first item in the array,
// assuming you don't have a $row->batchid of 0 in your results.
$data[0] = 'SELECT';
foreach ($records->result() as $row)
{
$data[$row->batchid] = $row->batchname;
}
return ($data);
}
And this in my view file
<?php echo form_dropdown('batchid', $dropdown_batchlist,'', 'class="required"' ); ?>
The Problem is Solved
I have figured out the problem. The view file was okay, all I had to do is replace $data[0] = 'SELECT'; with
$data[' '] = 'SELECT';
Thanks

Try setting the attributes using an associative array:
$attributes = array(
'name' => 'batchid',
'class' => 'required',
'options' => $dropdown_batchlist
);
echo form_dropdown($attributes);

Related

How to create filter with easy way in laravel 8 using controller and checkbox

I am creating filter for the products, I tried using jquery for this before but I am not able to fix the pagination in laravel. So, I am trying this to fix the pagination as well as reduce the database query, bcoz in jquery everytime I click on any category or sub category, then it hits the database so the number of execution was more, So I replace the jquery and trying to use the button to do the same. But stuck with the array.
Can anyone help me with this?
$category = ["p1","p2","p3"];
$sub_category = ["c1","c2","c3","c4"];
$data = [];
$count = 0;
foreach ($cate as $category){
$data2 =[];
$count1 = 0;
foreach ($sub_cate as $sub){
$data2[] = [
'sub_category_id' => $category.$count1++,
'sub_category' => $sub,
'url' => $category.'|'.$sub
];
}
$data[] = [
'category_id' => 'category_'.$count++,
'category' => $category,
'sub_category' => $data2
];
}
In blade file :
#foreach($filters as $filter)
<div class="custom-control custom-checkbox mb-2">
<input type="checkbox" class="custom-control-input category_filter1" id={{$filter["category_id"]}} name="category_filter[]" value="{{$filter["category"]}}">
<label class="custom-control-label w-100" for="{{$filter["category_id"]}}">{{$filter["category"]}}</label>
#foreach($filter["sub_category"] as $sub)
<div class="custom-control custom-checkbox mb-2">
<input type="checkbox" class="custom-control-input category_filter1" id={{$sub["sub_category_id"]}} name="sub_category_filter[]" value="{{$sub["url"]}}">
<label class="custom-control-label w-100" for="{{$sub["sub_category_id"]}}">{{$sub["sub_category"]}}</label>
</div>
#endforeach
</div>
#endforeach
After using this code I am getting this type of data :
{"category_filter":["p1","p2"],"sub_category_filter":["p1|c1","p1|c2","p1|c3","p1|c1"]}
So basically the array structure is like this :
For now everything looks nice but, When I try to combine the array into once then it look some time to sort and rearrange itself, So it there any easy way to this, Each time I change the filters it will take time and then it fetch result from the database. For some reason I thought that URL which is custom made will help me but it only taking us to the wrong direction.
apply condition in conrtoller like this
if($request->input('category_filter') == "p1"){
if($request->input('sub_category_filter') == "p1|c1"){
... do your code as per your need
}
}
I share Sample Example:
assume I want to filter data like All, approved, pending, decline... then I write script in controller like this
if($request->input('filtertype')){
$filtertype = $request->input('filtertype');
if($filtertype == "All"){
$deals = Deal::orderBy('updated_at', 'desc')->get();
}else{
$deals = Deal::where('deal_isApproved', '=', $filtertype)
->orderBy('updated_at', 'desc')->get();
}
}
return view('admin.deals.index',compact('deals'));

gridview check box multi delete in yii2

i simply want to have a gridview that has checkbox column in front of each row and my admins can delete row by check all or check one or check how many box they disire and then by click on delete button all checked row remove from their view
in the back its important to update their delete column to 1 a row not delete
here is my code for delete one id
controller(ignore persian words)
public function actionDelete($id=[])
{
$model = \Yii::$app->db->createCommand()
->update('tbl_post',['Delete'=>1],['id'=>$id])->execute();
if($model==true){
\Yii::$app->session->setFlash('با موفقیت نیست شد');
}else{
\Yii::$app->session->setFlash('با موفقیت نیست نشد');
}
return $this->redirect('index');
}
here is view(ignore persian words)
//in baraye ine ke form taiid shod payam bede
foreach (Yii::$app->session->getAllFlashes() as $key => $message) {
echo '<div class="alert alert-' . $message . '">' . $key . '</div>';
}
//-------------------------table it self
echo \yii\grid\GridView::widget([
'dataProvider' => $adp,
'caption' => 'لیست تمامی محتوا ها',
'captionOptions' => ['id' => 'atro-caption'],
'headerRowOptions' => ['class' => 'atro-th'],
'columns' => [
['class' => \yii\grid\SerialColumn::className(),],
['class' => \yii\grid\CheckboxColumn::className(),
'checkboxOptions' => function ($a) {
return ['value' => $a->id];
}],
'Title',
'FK_PostType',
'FK_Author',
]
]);
Before I suggest you anything about your problem you should know the basic rules of programming that never use reserved keywords for function naming variable or database field names, you have used the Delete as a column name you should change it immediately to something like is_deleted. i will be using this name in my example reference.
About your problem, you have 2 ways to do it.
Add a button and bind javascript click event to it which will serialize all the selected checkboxes and then use an ajax post request to submit the selected ids and mark them delete.
Wrap your Gridview inside a form tag and then use a submit button to submit that for to the delete action.
I will demonstrate the first option to you
add the button on top of your GridView
<?=Html::button('Delete', ['class' => 'btn btn-danger', 'id' => 'delete'])?>
Then assign an ID to the pjax container
<?php Pjax::begin(['id' => 'my-grid']);?>
Paste this javascript on top of your view but update the url of the ajax call to your actual controller/delete action
$this->registerJs('
$(document).on("click","#delete",function(e){
let selected=$(".grid-view>table>tbody :input");
let data=selected.serialize();
if(selected.length){
let confirmDelete = confirm("Are you sure you want to delete?");
if(confirmDelete){
$.ajax({
url:"/test/delete",
data:data,
dataType:"json",
method:"post",
success:function(data){
if(data.success){
$.pjax({container:"#my-grid"});
}else{
alert(data.msg);
}
},
error:function(erorr,responseText,code){}
});
}
}else{
alert("select someitems to delete");
}
});
', \yii\web\view::POS_READY);
And change your delete action to the following, try using transaction block so that if something happens in the middle of the operation it will revert all the changes back, change the model name and namespace to the appropriate model, I assumed your model name is Post.
public function actionDelete()
{
if (Yii::$app->request->isPost) {
$selection = Yii::$app->request->post('selection');
$response['success'] = false;
$transaction = Yii::$app->db->beginTransaction();
try {
\frontend\models\Post::updateAll(['is_deleted' => 1], ['IN', 'id', $selection]);
$response['success'] = true;
$transaction->commit();
} catch (\Exception $ex) {
$transaction->rollBack();
$response['msg'] = $ex->getMessage();
}
echo \yii\helpers\Json::encode($response);
}
}

Yii ClinkPager doesn't work on Ajax Request

Firstly, when the page gets loaded, ClinkPager works properly with all the paging correctly displayed.
But when Ajax Request is sent, the results get populated correctly with all the paging.
But clicking on the next or another page in the Paging, the previous data gets loaded and also paging shows different sequence.
/*Controller action to fetch the records and apply the pagination*/
//---------------------------------------------------------------
public function actionGetUser($user_id=null)
{
$user_domain= (isset($_POST['user_domain'])?$_POST['user_domain']: null);
$model=new UserSearch();
$criteria=new CDbCriteria();
//If Category/Title are also specified for search, then its an Ajax request.
if((isset($_POST['ajax_search'])) && ($_POST['ajax_search']==1))
{
//Change the search criteria accordingly
$criteria->select="*";
if($user_domain!= null)
{
//Adding criteria to search for ideas of specific domain
$criteria->addCondition("user_domain=".$usr_domain);
}
}
//Retrieve the users.
$searchData = $model->search();
//Count the no. of results retrieved.
$count=UserSearch::model()->count($criteria);
//Enable pagination
$pages=new CPagination($count);
$searchData->setPagination($pages);
$pages->applyLimit($criteria);
//Search for ideas satisfying that criteria
$models=userSearch::model()->findAll($criteria);
if((isset($_POST['ajax_search'])) && ($_POST['ajax_search']==1))
{
//Rendering the respective page
$this->renderPartial('renderOnAjax', array(
'user' => $models,
'pages' => $pages,
'user_count'=>$count
));
}
else
{
//Rendering the respective page
$this->render('render', array(
'user' => $models,
'pages' => $pages,
'user_count'=>$count
));
}
}
//------------------------------------------------------------
/*render page*/
//------------------------------------------------------------
<div>
<div class="userInfo" id="user_search_result">
<?php $this->renderPartial("renderOnAjax",array('user'=>$user, 'pages'=>$pages));?>
</div>
</div>
//------------------------------------------------------------
/*renderOnAjax Page*/
//------------------------------------------------------------
<?php
$i=0;
$count=count($user);?>
<?php while($i!=$count) {?>
<?php $row=$count[$i];?>
<div class="Box">
/*Some contain to display...*/
</div>
<?php $i++;?>
<?php } ?>
<div class="row">
<?php $this->widget('CLinkPager', array(
'pages' => $pages
));
?>
</div>
//---------------------------------------------------------
try
<?php $this->renderPartial("renderOnAjax",array('user'=>$user, 'pages'=>$pages),false,true);?>
Here is official documentioan for renderPartial
public string renderPartial(string $view, array $data=NULL, boolean $return=false, boolean $processOutput=false)
$view=string name of the view to be rendered. See getViewFile for details about how the view script is resolved.
$data=array data to be extracted into PHP variables and made available to the view script
$return=boolean whether the rendering result should be returned instead of being displayed to end users
$processOutput=boolean whether the rendering result should be postprocessed using processOutput.
{return} string the rendering result. Null if the rendering result is not required.
EDIT:
The above scheme works for ajax call renderPArtials. You should try this where you are rendering ajax request in controller action like
$this->renderPartial('renderOnAjax', array(
'user' => $models,
'pages' => $pages,
'user_count'=>$count
),false,true);

CakePHP setting up dependent AJAX dropdown

I have done a lot of research, tried to apply a few different examples but it seems that nothing really works.
So I have the following 3 models: Customers, Projects and Events. Customers have many Projects and Projects have many Events.
While creating an Event, I would like a user to select a Customer from a dropdown list and then the user should be provided with a list of Projects that belong to the selected Customer. The closest I have got to is the following. I do not have experience with AJAX, so that really is a hard nut to brake.
Action in the Porject's controller:
public function getbycustomer(){
$customer_id = $this->request->data['Event']['customer_id'];
$projects = $this->Project->find('list', array('conditions'=>array('Project.customer_id' => $customer_id), 'recursive' => -1));
$this->set('projects', $projects);
$this->layout = 'ajax';
}
View for this action is the following:
<?php foreach ($projects as $key => $value): ?>
<option value="<?php echo $key; ?>"><?php echo $value; ?></option>
<?php endforeach; ?>
And here is the snippets from the view for adding an event:
echo $this->Form->input('customer_id');
echo $this->Form->input('project_id');
//form continues and at the end of a page there is the AJAX call
$this->Js->get('#EventCustomerId')->event('change',
$this->Js->request(array(
'controller'=>'projects',
'action'=>'getbycustomer'
), array(
'update'=>'#EventProjectId',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true
))
))
);
Any help is much much appreciated as I do not even know the proper way for debugging it, so I could provide more valuable information.
go to this. this helped me to do the dependent drop down list. it provies a details step by step process.
I think you need to set autoRender to false otherwise it will try to render the template at app/View/Project/getbycustomer.ctp. Also, you probably want to return or print JSON. Ther are probably several ways to do this, but I have something similar that is working and the controller action is basically this:
public function getbycustomer() {
$this->autoRender = $this->layout = false;
$customer_id = $this->request->data['Event']['customer_id'];
$projects = $this->Project->find('list', array('conditions'=>array('Project.customer_id' => $customer_id), 'recursive' => -1));
$this->set('projects', $projects);
echo json_encode(array('html' => $this->render('your_partial_template')->body())); // This template would be in app/View/Project/json/
}
Then in your Ajax call there should be a 'success' callback that handles the JSON returned:
success: function(data) {
$('#EventProjectId').html(data.html); // assuming this an empty container
}
Also, unless your projects table is only two columns the result of your find is probably not what you're expecting. Change it to
$projects = $this->Project->find('list', array('conditions'=>array('Project.customer_id' => $customer_id), 'fields' => array('id', 'name_or_whatever', 'recursive' => -1));
Then in your partial template you can use the form helper:
<?php echo $this->Form->input('Projects.id', array('options' => $projects)); ?>

Form validation error not outputted in PyroCMS

Using PyroCMS 1.3.1 I've built a model that's pretty much a copy-paste version of the included contact model, but with a few tweaks. When all fields are inputted correctly everything works as expected. If a field is left out or incorrectly filled in, the form does not submit - just as expected.
However, I can't seem to get the form validation message to be outputted and this is driving me crazy. I'm sure I've just missed something very basic so if anyone could point it out I'd be grateful.
View file (form.php) contains this
<?php if (validation_errors()): ?>
<div class="error-box">
<?php echo validation_errors(); ?>
</div>
<?php elseif (isset($messages['error'])): ?>
<div class="error-box">
<p><?php echo $messages['error']; ?></p>
</div>
<?php endif; ?>
Controller (plugin.php) looks like this
class Plugin_mycustommodule extends Plugin {
private $rules = array(
array(
'field' => 'firstname',
'label' => 'lang:mycustommodule_firstname_label',
'rules' => 'required|trim|max_length[80]'
),
/* ... snip ... */
array(
'field' => 'license',
'label' => 'lang:mycustommodule_license_label',
'rules' => 'required'
)
);
public function __construct()
{
$this->lang->load('mycustommodule');
}
function form()
{
$this->load->library('form_validation');
$this->load->helper('form');
$this->form_validation->set_rules($this->rules);
// If the user has provided valid information
if ($this->form_validation->run())
{
/* ... Custom processing here ... */
// The try to send the email
if ($this->_send_email())
{
$message = $this->attribute('confirmation', lang('mycustommodule_sent_text'));
// Store this session to limit useage
$this->session->set_flashdata('success', $message);
redirect(current_url());
}
else
{
$message = $this->attribute('error', lang('mycustommodule_error_message'));
$data['messages']['error'] = $message;
}
}
// Set the values for the form inputs
foreach ($this->rules as $rule)
{
$form_values->{$rule['field']} = set_value($rule['field']);
}
$data['form_values'] = $form_values;
return $this->module_view('mycustommodule', 'form', $data, TRUE);
}
So it turns out that while I was working on customizing the CodeIgniters language files I must have messed up the upload of form_validation_lang.php because all entries was empty i.e. $lang['required'] = '';
So basically the validator looked for the error message, found an empty string, which was trimmed from being outputted. As suspected something silly, just not in the place I expected.
Let's hope this post will save someone else the trouble.

Resources