I have data in an array that contains hotels' names with their id. I want to place them in my select where I will display only the city an grab the id to do ajax and display rooms name. The problem is it is displaying both the name of the hotel and the id array in my dropdown.
this is my controller.
foreach ($hotel as $nam ){
$hotel_nam[]=$nam->id;
$hotel_nam[]=$nam->hotel_name;
}
return $hotel_nam;
this is my drop down
{!! Form::select('hotel_name',$hotel_nam,'S', array('style'=>' Border:none; ', 'id' => 'hotel_id', 'onchange'=>"showRooms(this.value)"));!!}
$hotelLists = [''=>'--Select Hotel--'];
foreach ($hotel as $nam) {
$hotelLists[$nam->id] = $nam->hotel_name;
}
{!! Form::select('hotel_name',$hotelLists,'', array('style'=>' Border:none; ', 'id' => 'hotel_id', 'onchange'=>"showRooms(this.value)"));!!}
Related
I'm want to use paginate in laravel but didn't work perfectly. When i paginate the filtered data it worked fine, but only for the first page.The problem is when i moved to the second page, it will display the second page of all data not the filtered data. i want it so the second page will display the second page of filtered data
in blade.php I'm using links to call the paginate(for moving page)
<div class="paginate">
{{ $data->links() }}
</div>
Here's the filter controller
function filter(Request $request){
$data = profiles::when($request->has('pNamaLengkap'), function($query) use ($request){
$query->where('pNamaLengkap','like','%'.$request->pNamaLengkap.'%');
});
if($request->pJobDescription != 'All'){
$data = $data->where('pJobDescription','like','%'.$request->pJobDescription.'%');
}
if($request->pUnitKerja != 'All'){
$data = $data->where('pUnitKerja','like','%'.$request->pUnitKerja.'%');
}
if($request->pDirectorate != 'All'){
$data = $data->where('pDirectorate','like','%'.$request->pDirectorate.'%');
}
if($request->pRank != 'All'){
$data = $data->where('pRank','like','%'.$request->pRank.'%');
}
return view('export', [
'data' => $data->paginate(5),
'jobdescription' => jobdes::all(),
'unitkerja' => unitkerja::all(),
'direktorat' => direktorat::all(),
'rank' => rank::all(),
'oldjob' => $request->pJobDescription,
'oldunit' => $request->pUnitKerja,
'olddir' => $request->pDirectorate,
'oldrank' => $request->pRank,
'oldname' => $request->pNamaLengkap
]);
// return redirect('export')->with([
// 'data' => $data,
// 'jobdescription' => jobdes::all(),
// 'unitkerja' => unitkerja::all(),
// 'direktorat' => direktorat::all()
// ]);
}
I'll make an example from a picture
Filtered JobDescription Page 1
Page 2 that reset the filter and display all data
in the URL parameter it change it from
http://127.0.0.1:8000/filterexport?pNamaLengkap=&pJobDescription=Full+Stack+Developer&pUnitKerja=All&pDirectorate=All&pRank=All&export=Filter
into
http://127.0.0.1:8000/filterexport?page=2
for extra note, the paginate is working but just didn't work when you want to view the second page because somehow it reset the input filter
Thank you for reading this page, i really need help in this one
$data->paginate(15)->withQueryString();
use withQueryStrings() method with paginated data.
another solution is replacing
{{ $data->links() }}
to the
{{ $data->appends(Request::except('page'))->links() }}
For lower versions of Laravel, you can use this:
{!! str_replace('/?', '?', $data->appends(Input::except('page'))->render()) !!}
I am trying to fetch the list of city_name (column) from my table Cities and display that list into my dropdown
I write the following code in my controller method
namespace App\Controller;
use App\Controller\AppController;
class PrimeUsersController extends AppController
{
public function initialize()
{
parent::initialize();
$this->viewBuilder()->setlayout('primewishsLayout');
$this->loadModel("Cities");
$this->loadModel("States");
$this->loadModel("Users");
}
public function addnew()
{
// $this->autoRender=false;
$this->set('title',"Add User/Company");
$digits_needed=10;
$random_number=''; // set up a blank string
$count=0;
while ( $count < $digits_needed )
{
$random_digit = mt_rand(0, 9);
$random_number .= $random_digit;
$count++;
}
$this->set("rendomReg",$random_number);
// $view=$this->States->find()->toArray();
// print_r($view);
// city list
$fieds = array('Cities.city_name');
$city = $this->Cities->find()->select(['city_name'])->enableHydration(false)->toList();
// print_r($city);die;
$this->set(compact('city'));
}
}
and this is my dropdown where I want to show my item list in addnew.ctp
<div class="col-md-3 pl-1">
<div class="form-group">
<label>City:</label>
<?php
echo $this->Form->control('City',array(
'options' => $city,
'value'=>$option,
'required'=>'required',
'class'=>'form-control',
'label'=>false,
'default' => $option['select']
));
?>
</div>
</div>
I am able to fetch the list but when I click on dropdown the list display like this:-
1
Kanpur
2
Lucknow
3
Delhi
please help me out..
According to Cakephp
CakePHP provides a simple to use method for generating ‘lists’ of
data. It is often useful to generate an associative array of data from your application’s data. For example, this is very useful when creating elements.
So to get the list of cities you can use list in your find query. This will give you an associative array of id and city name from your cities table.
PrimeUsersController.php
$city = $this->Cities->find('list')->find('list', [
'keyField' => 'id', // specify column name that you used used as city id in cities table
'valueField' => 'city_name' // specify column name that you used used as city name in cities table
])->toArray();
$this->set(compact('city'));
addnew.ctp
$this->Form->select(
'city',
$city,
['required'=>'required',
'class'=>'form-control',
'label'=>false,
'empty' => 'Select City']
);
Cakephp -> Retrieving Data & Results Sets -> Finding Key/Value Pairs
Hope this will help!
Try something like this:
$this->Form->select(
'city',
$city,
['required'=>'required',
'class'=>'form-control',
'label'=>false,
'default' => ':Select:']
);
More instructions: https://book.cakephp.org/3.0/en/views/helpers/form.html#common-options-for-specific-controls
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);
}
}
I am creating project with laravel 5, i did store checkbox array value into table using below's code
$permission_id = Input::get('permission_id');
if(is_array($permission_id))
{
$permission_id = implode(',', $permission_id);
}
$userpermissionlist->permission_id = $permission_id ;
it's stored value like 2,3,4 now i need to explode this value and selected checkbox value will be checked.. how can i do that..My view code is
{!! Form::checkbox('permission_id[]', $userpermission->id) !!}
Setting the third parameter to true in checkbox() method will mark the checkbox as checked. Assuming you have $checked_permission_ids which is an array of all the checked ids, you could do this:
#foreach( $user_permissions as $userpermission )
{!! Form::checkbox('permission_id[]', $userpermission->id, in_array( $userpermission->id, $checked_permission_ids ) ) !!}
#endforeach
I am working with laravel, right now, i am making an user registry Form, i am relating the state and its cities, so, i need to change a select field values according the state that user chooses.
I have something in the form:
{{ Form::select('city', $city, array('id', 'city')}}
If i use the {{Form::select}} fields in conventional way it charges all the cities from one state, so, when the user select a state, it must change the list of cities in the select field.
I searched but i didn't find any. How can i do that?
thanks.
You can use ajax with jQuery.
In your view set an event when the state change, like this:
$(document).on('change', '#state_id', function (e) {
// empty the select with previous cities if we have.
$('#cities').empty();
$.ajax({
type: "POST",
dataType: "json",
// actions is a controller
// cities is a method of actions controller
url : "{{ URL::to('actions/cities') }}",
//here we set the data for the post based in our form
data : $('#MyFormID').serialize(),
success:function(data){
if(data.error === 0 ){ // all was ok
for (var i = 0; i < data.cities.length; i++) {
$('#cities').append("<option value='"+data.cities[i].id+"'>"+data.cities[i].city_name+"</option>")
}
}else{
alert(data);
}
},
timeout:10000
});
});
actions/cities controller
//remember, this is a post method
public function postCities(){
// validate
$validator = Validator::make(Input::all(),
array(
'state_id' => 'required|integer'
));
if ($validator->fails()) {
return Response::json(array('error' => 1, 'message' => 'State is required'));
}
//City is your model, I assumes that you pkey is ID and the city name is city_name and your fkey is state_id
$cities = City::where('state_id', '=', Input::get('state_id'))->get();
return Response::json(array('error' => 0, 'cities' => $cities));
}
public function getCities($province_id)
{
$cities = Cities::where('province_id', '=', $province_id)->get(['id', 'name']);
return Response::json(array('error' => 0, 'cities' => $cities));
}
You might want to check a sample vue component that ships with my package Laravel Cities that performs exactly what you are trying to build.
This is a simple package that allows you seed localy all the cities of any country on the world (provided by geonames.org) and perform any query with the provided Eloquent model. It exposes an HTTP API and a vue component that allows you to select any city through a series of steps.
You can insert it in your forms like any other input field:
<form action="post-url" method="POST">
<geo-select></geo-select>
<!-- Add more form fields here... -->
<input type="submit">
</form>
With the provided Eloquent model You can perform queries like this:
// Get the States of USA in aplhabetic order
Geo::getCountry('US')
->children()
->orderBy('name')
->get();
Sorry, no demo yet, but you can check some sceenshots on the github page...