How do I pass to codeigniters controller a parameter via URL?
I use IgnitedTables to display jquery DataTable. Actually I use ajax to populate table (cms_datatable()) I would like to pass somehow a language parameter via url to can filter content on language
I have the following
public function cms($cms_lang = '') {
$this->cms_lang = $this->session->userdata('cms_lang');
if(isset($cms_lang)){
$this->cms_lang['current_lang'] = $cms_lang;
} else {
$this->cms_lang['current_lang'] = 'de';
}
$tmpl = array('table_open' => '<table id="cms_table" border="0" cellpadding="2" cellspacing="2" class="table table-striped table-primary table-condensed">');
$this->table->set_template($tmpl);
$this->table->set_heading('<input name="id[]" type="checkbox">', 'Title', 'SEF URL', 'Letztens bearbeitet', 'Status');
$this->load->view('admin/admin', $this->data);
}
public function cms_datatable() {
error_reporting(-1);
// var_dump($this->cms_lang['current_lang']); returns NULL
$this->datatables->select('id,title,sef_title, creation_date,status')
->edit_column('title', '$2', 'id, title')
->unset_column('creation_date')
->add_column('creation_date', '<span class="label label-danger">$1</span>', 'creation_date')
->unset_column('status')
->add_column('status', get_buttons('$1'), 'id')
->from('ci_content')
->where('language', $this->cms_lang);
echo $this->datatables->generate();
}
than I try to override the default value of variable $lang like
domain/admin/cms/en
but my var_dump($lang) shows the defualt value
routed as
$route['admin/cms'] = "admin/dashboard/cms";
$route['admin/cms/(:any)'] = "admin/dashboard/cms/$1";
your controller fn name is cms_datatable but you're not calling it.
Try using the url routes:
$route['admin/cms'] = "admin/dashboard/cms_datatable";
$route['admin/cms/(:any)'] = "admin/dashboard/cms_datatable/$1";
That route assumes that:
admin is your folder
dashboard is your controller
cms_datatable is your controller fn
Also, re-reading your question, I am not sure why you want to pass language variables to EACH controller? Just set it in session and check it that way. Override the default if the session has a different language defined. Having every controller check this is not good form.
Related
I have some filters on a web page (checkboxes) and I modify the result list by ajax POST method. Is there a way that somehow I save the page state and send the URL link to someone so they open it in that state? Any help is appreciated.
By the way I'm using Laravel.
You can use parameters :
test.com/page?checkbox1=checked&checkbox2=checked
In your Laravel controller you can do this :
public function page($request) {
$checkboxes = array();
if ($request->has('checkbox1')) {
$checkboxes[] = true;
}
if ($request->has('checkbox2')) {
$checkboxes[] = true;
}
// ... and so on.
return view('page', compact('checkboxes'));
}
And set your php page like this :
<input type="checkbox" <?php checkboxes[$i++] ? 'checked' : '' ?> >
You can set the checkbox as parameter in the URL, and when the user go to your address, check if there is any of your params.
if so - set the checkboxes as you wish
just to get the general idea..
function getUrlParams(requested_param){
//check for params
return result;
}
if (getUrlParams(myCheckBox)){
$('#checkbox_on_page').prop( "checked", true );
}
I'm trying to use jtable plugin in framework codeigniter but i got a problem. I'm confused how to pass variable from view (jtable javascript code) to controller and to pass json_encode from controller to view.
Here are my code.
in my view page(Attendance_view.php).
[html code]
<input style="width:100px" type="text" id="from" name="from" value="<?php echo date("Y-m")."-01";?>">
[js code]
//Prepare jTable
var base_url ="<?=base_url()?>";
$('#TableContainer').jtable({
title: 'Attendance',
paging: true,
sorting: true,
defaultSorting: 'month ASC',
selecting: true, //Enable selecting
multiselect: true, //Allow multiple selecting
selectingCheckboxes: true, //Show checkboxes on first column
actions: {
listAction: '<?=base_url()?>index.php/Attendance_controller/listRecord',
createAction: '<?=base_url()?>index.php/Attendance_controller/create',
updateAction: '<?=base_url()?>index.php/Attendance_controller/update',
deleteAction: '<?=base_url()?>index.php/AttendanceAbsensi_controller/delete'
},
....//another field here
});
//Load attendance from server
$('#TableContainer').jtable('load',{
month:$("#from").val()
});
in my controller(Attendance_controller.php)
function listRecord()
{
$this->load->model('Attendance_action');
$jTableResult=$this->Attendance_action->list_record();
$data['jTableResult']= json_encode($jTableResult);
$this->load->view('Attendance_view',$data['jTableResult']);
}
in my model (Attendance_action.php)
function list_record()
{
//get post variable
$date=$this->input->post('month'); // i can't get the value.
//Get record count
$result = //my query here[select "some data" from "mytable" where month='$date']
$recordCount = mysql_num_rows($result);
//Add all records to an array
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['TotalRecordCount'] = $recordCount;
$jTableResult['Records'] = $rows;
return $jTableResult;
}
When i load the controller page, the error message from jtable occured "An error occured while communicating to the server". Please help. thanks.
Why your using jtable .can you use Jquery Datatbles here having ignited Datatables Library using that one we can implement crud functionality simple
you can interest please check it once the bellow url
https://github.com/IgnitedDatatables/Ignited-Datatables/
http://datatables.net/examples/data_sources/server_side.html
https://ellislab.com/forums/viewthread/160896/
i am personal y like jquery data-tables.just check it once
First load view page in separate function .In that page you call call your crud Urls
Change like this your controller
function list()
{
$this->load->view('Attendance_view');
}
function listRecord()
{
$this->load->model('Attendance_action');
$jTableResult=$this->Attendance_action->list_record();
print_r(json_encode($jTableResult));
}
Note : Can you please check it once this here mentioned clearly how to implement this one
http://jtable.org/GettingStarted
i want to share my code. Now the problem fixed. I just change the controller code like this. Add "exit();" in controller.
function index()
{
$this->load->view('Attendance_view');
}
function listRecord()
{
$this->load->model('Attendance_action');
$jTableResult=$this->Antendance_action->list_record();
print_r(json_encode($jTableResult));
exit();
}
I have a search result view that has a generated list of tables from another sites API. I'm trying to pass off the Artist ID to another next action via GET. The Artist ID will be then used to interact with the API.
I try to pass off the Artist ID like so but I receive a 'array_combine(): Both parameters should have an equal number of elements'.
The view file in question:
#foreach($parser->Artists->Artist as $Artist)
<table class = "table table-striped">
<thead>
{{ var_dump(strval($Artist['ID']))}}
<h3>{{ $Artist['ListName'] }}</h3>
</thead>
<tbody>
The vardump was to test that a string was in fact being passed off to the action(). I can confirm that it is, before it was a simple XML object.
Here's the corresponding route:
Route::get('/artist/detail/{$artist}','ArtistController#detail');
And the controller action:
<?php
// app/controllers/ArtistController
class ArtistController extends BaseController
{
public function detail($Artist) {
return 'Artist ID is ' . $Artist;
}
{
The problem was that Laravel was too smart. My $Artist variable was not read as a string but as a model because of the binding the routes file.
routes.php
Route::model('artist','Artist');
I changed $Artist from $Artist_ID and it worked just fine.
I have a Yii form which calls a render partial from another model (team has_many team_members). I want to call via ajax a partial view to add members in team/_form. All works (call, show, save) except for ajax validations (server and client side). If i submit form, member's model isn't validating, even in client side, it's not validating the required fields.
Any clue?
//_form
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'team-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
'validateOnChange'=>true
),
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>
//Controller
public function actionMember($index)
{
$model = new TeamMember();
$this->renderPartial('_member',array(
'model'=> $model, 'index'=> $index
)
,false,true
);
}
public function actionCreate()
{
$model=new Team;
$members = array();
if(isset($_POST['Team']))
{
$model->attributes=$_POST['Team'];
if(!empty($_POST['TeamMember'])){
foreach($_POST['TeamMember'] as $team_member)
{
$mem = new TeamMember();
$mem->setAttribute($team_member);
if($mem->validate(array('name'))) $members[]=$mem;
}
}
$this->redirect(array('team/create','id'=>$model->id,'#'=>'submit-message'));
}
$members[]=new TeamMember;
$this->performAjaxMemberValidation($members);
$this->render('create',array(
'model'=>$model,'members'=>$members
));
}
//_member
<div class="row-member<?php echo $index; ?>">
<h3>Member <?php echo $index+1; ?></h3>
<div class="row">
<?php echo CHtml::activeLabel($model, "[$index]name",array('class'=>'member')); ?>
<?php echo CHtml::activeTextField($model, "[$index]name",array('class'=>'member')); ?>
<?php echo CHtml::error($model, "[$index]name");?>
</div>
</div>
ProcessOutput was set to true. No dice.
Switch renderPartial() to render(). No dice.
If you will look at the CActiveForm::run:
$cs->registerCoreScript('yiiactiveform');
//...
$cs->registerScript(__CLASS__.'#'.$id,"jQuery('#$id').yiiactiveform($options);");
Then you will understand that you validation will not work, because you render partial and not the whole page. And these scripts show up at the bottom of the page. So you should solve this by execute these scripts.
After you partial is rendered, try to get activeform script which should be stored at the scipts array:
$this->renderPartial('_member',array('model'=> $model, 'index'=> $index));
$script = Yii::app()->clientScript->scripts[CClientScript::POS_READY]['CActiveForm#team-form'];
after, send it with rendered html to page:
echo "<script type='text/javascript'>$script</script>"
Also remember before you will append recieved html on the page you should include jquery.yiiactiveform.js, if you not already did it(by render another form, or registerCoreScript('yiiactiveform')), on the page from calling ajax request. Otherwise javascript error will raised.
Hope this will help.
Edit:
Sorry I'm not understood that you are render part of form and not the whole. But you validation will not work exactly with the same issue. Because jQuery('#$id').yiiactiveform($options); script was not created for the field.
The actual problem is that the ActiveForm saves its attributes to be validated in the "settings" data attribute. I see you are already using indexes so what you need to add the new elements to this settings object in order for the validation to work. After the ajax response this is what must be done:
//Get the settings object from the form
var settings = $("#form").data('settings');
//Get all the newly inserted elements via jquery
$("[name^='YourModel']", data).each(function(k, v) {
//base attribute skeleton
var base = {
model : 'YourModel',
enableAjaxValidation : true,
errorCssClass : 'error',
status : 1,
hideErrorMessage : false,
};
var newRow = $.extend({
id : $(v).attr('id'),
inputID : $(v).attr('id'),
errorID : $(v).attr('id') + '_em_',
name : $(v).attr('name'),
}, base);
//push it to the settings.attribute object
settings.attributes.push(newRow);
});
//update the form
$("#form").data('settings', settings);
```
This way the ActiveForm will be aware of the new fields and will validate them.
Well, setting processOutput to true in renderPartial (in order to make client validation works on newly added fields) will not help in this case since it will only work for CActiveForm form and you don't have any form in your _member view (only input fields).
A simple way to deal with this kind of problem could be to use only ajax validation, and use CActiveForm::validateTabular() in your controller to validate your team members.
It's my first post in here and I haven't yet figured out to format my post properly yet, but here it goes.
So basically I can only get my code to work if i point directly to a php-file. If I try to call a method within my controller, nothing seems to happen.
My JavaScript:
$(document).ready(function() {
$(".guide_button").click(function(){
var id = $(this).text();
var data = {};
data.id = id;
$.getJSON("/guides/hehelol", data, function(response){
$('#test').text(response.id);
});
return false;
});
});
My markup:
<div id="content_pane">
<ul>
<li>RL</li>
<li>LG</li>
<li>RG</li>
<li>SG</li>
<li>GL</li>
<li>MG</li>
</ul>
</div>
<div class="description">
<h3>Description</h3>
<p id="test">This text area will contain a bit of text about the content on this section</p>
</div>
My Controller:
<?php
class Guides extends CI_Controller {
public function Guides()
{
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
}
public function index()
{
$this->load->view('guides_view');
$title = 'Some title';
}
public function hehelol() //The controller I am desperatly trying to call
{
$id = $_GET['id'];
$arr = array ('id'=>$id);
echo json_encode($arr);
}
}
It might be my controller I have done something wrong with. As it is the code only works if create a hehelol.php file and refer to it directly like this.
$.getJSON("hehelol.php", data, function(response){
$('#test').text(response.id);
});
Anyone who knows what I need to do to make my controller work properly? Help please! :)
i just put your exact code in its entirety in my codeigniter app and it worked for me. Meaning I used this: ...$.getJSON("/guides/hehelol",...
Because you are making a $_GET request, you have to enable query strings.
In your config.php file, make sure this line is set to TRUE:
$config['allow_get_array']= TRUE;