I am using codeigniter pagination library and doing update and delete through form. The problem is when I delete or update any record after delete or update I redirected back to 1st page even if I am at 4th page. How I can redirected to the same page at which I have done update or delete.
Here is my controller code for update and delete functions:
public function update_att(){
if(isset($_POST['update'])){
$u_id = $_POST['at_id'];
if($_POST['status']=="Present"){
$data = array(
'status'=>"Absent"
);
$this->db->where('at_id', $u_id);
$this->db->update('attendence', $data);
}elseif ($_POST['status']=="Absent") {
$data = array(
'status'=>"Present"
);
$this->db->where('at_id', $u_id);
$this->db->update('attendence', $data);
}
redirect("usr/att_list", "refresh");
}
}
public function delete_att(){
if (isset($_POST['delete'])) {
$at_id = $_POST['at_id'];
$this->db->where('at_id', $at_id);
$this->db->delete('attendence');
}
redirect("usr/att_list" );
}
Currently I am redirecting to the first page , any suggestion how I redirect to that page where I have done delete or update.
Add <input type='hidden' name='current_page' value='<?php echo $current_page?>' /> to your form.
Keep in mind you need to populate $current_page with something like
$current_page = ''; // empty means first page
if( isset($_REQUEST['current_page'] ){
$current_page = $_REQUEST['current_page'];
}
Then based on your sample you just modifiy the redirect path as follows (for both your functions):
public function delete_att(){
if (isset($_POST['delete'])) {
$at_id = $_POST['at_id'];
$this->db->where('at_id', $at_id);
$this->db->delete('attendence');
}
redirect("usr/att_list".(strlen($current) ? "?".$current : "" );
}
Note:
Your path to your page should look something like this domain.com/controller/your_page_with_pagination/?current_page=A_NUMBER then in your controller/your_page_with_pagination you adjust the data you wish to output based on $_GET['current_page']
Edit based on your link:
public function att_list($id = ""){
/**
* Keep your data in array
*/
$this->data = array();
/**
* Add the page number ($id) to the array
* Check for url /:id first , or else check for a $_GET/$_POST current_page (this will be triggered when you submit your form)
*/
$this->data['current_page'] = is_numeric($id) ? $id : (isset($_REQUEST['current_page'] ? $_REQUEST['current_page']: 0);
/**
* This is your 'keep on the same page' line
* $this->data['current_page'] will act as an offset in your query
* You can read about 'offset' here https://www.w3schools.com/php/php_mysql_select_limit.asp
* $this->data['my_desired_records'] must be generated into your <form> ... </form> , and the same form must contain the input with name='current_page'
*/
$this->data['my_desired_records'] = $this->your_model->get_data($this->data['current_page']);
/**
* Pass the whole array into your view
*/
$this->load->view('path/to/view', $this->data);
}
Then in your view add in your form <input type='hidden' name='current_page' value='<?php echo $this->data['current_page']?>' />
Related
I'm trying to save the list of files in the post but it does not save the relationship.
I want to save the first post and then add the images inserted.
class SaveData extends ComponentBase {
public function onSubmitContact() {
/*
* This field: <input type="file" name="files[]" id='files' multiple="true"/>
*/
$files = Input::file('files');
$modelFiles = new MyModeToSave;
$modelRelation = new ModelToRelation;
foreach($files as $file):
$modelFiles->data = $file;
$modelFiles->save();
endforeach;
$modelRelation->title = post('title');
/* more fields */
$modelRelation->save();
$modelRelation->files()->add($modelFiles);
}
}
tanks
Code this is CMS OCTOBER
Not sure on your exact use case, but something like this should work:
//Pass your model id, and then find it in your function
$model = ModelToRelation::find(post('modelID'));
//commit all the files relations
$model->commitDeferred(post('_session_key'));
foreach($model->files() as $file) {
//now you can do stuff with the file...or model
}
I've created a widget with a CActiveForm in it. Everything works ok, but now i want to enable ajax validation for it.
The problem is that the output of my ajax validation is containing, besides the validation JSON string, all (well a part of it, since Yii::app()->end() stops the rest) of my html as well. Not weird, because i'm using it within a widget and the validation request is done to the controller/action where i've placed this widget on.
Is there some way to prevent outputting all the html, so a valid JSON string is returned?
I've already tried to set the validationUrl in the CActiveForm to another controller/action, but the problem is that i have to send the model with it and this model is determined in my widget and not on the validationUrl.
Widget:
public function run()
{
$model = new User;
$model->scenario = 'create';
$this->performAjaxValidation($model);
if (isset($_POST['User'])) {
$model->attributes = $_POST['User'];
if ($model->save()) {
}
}
$this->render('register-form', array(
'model' => $model
));
}
/**
* Performs the AJAX validation.
* #param User $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']))
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
Output of performAjaxValidation() (the ajax call):
.. more html here ..
<section class="box">
<h1>Register form simple</h1>
{"UserPartialSignup_email":["Email is geen geldig emailadres."]}
I solved it this way:
I've created an AJAX controller where the validation is done:
AjaxController:
/**
* Validates a model.
*
* Validates a model, POST containing the data. This method is usually used for widget based forms.
*
* #param $m model name which have to be validated
* #param $s scenario for this model, optional.
* #return string JSON containing the validation data
*/
public function actionValidate($m, $s = null)
{
if ($this->checkValidationData($m, $s) && isset($_POST['ajax']))
{
$model = new $m;
$model->scenario = $s;
echo CActiveForm::validate($model);
Yii::app()->end();
} else {
throw new CHttpException(500, 'No valid validation combination used');
}
}
You can give the model name and a scenario as GET parameters with it, i'm checking if this combination is allowed by the checkValidationData() method.
In the view of my widget where the CActiveForm is placed, i've added the validationUrl, referring to ajax/validate:
widgets/views/registerform.php:
<?php $form = $this->beginWidget('CActiveForm', array(
'id'=>'signup-form-advanced',
'enableAjaxValidation'=>true,
'clientOptions' => array(
'validationUrl' => array('ajax/validate', 'm' => get_class($model), 's' => 'create')
)
//'enableClientValidation'=>true,
)); ?>
I am new to php/codeignitor and trying to post changes on form checkboxes to my db. The row to modify is assigned by the gl_id below.
I am not sure how to use my update_checked function in the model to
post TRUE to each of these fields where gl_id =x and FALSE using to the remaining fields not in the array. I can create and view the array of checked values using $_POST['checked'] in the controller
and passing it to the model. Now I need to use this array to post to the db where gl_id = the value from the form in the view.
In View
<h1>Update GL id <?php echo $gl_field['gl_id'];?></h1>
<label>Stat</label>
<input type="checkbox" <?php if ($gl_field['stat'] == "TRUE") {echo "checked = checked";} ?>
name = "checked[]" id="stat" value= "stat" /><BR CLEAR="all">
<label>Exclude</label>
<input type="checkbox" <?php if ($gl_field['exclude'] == "TRUE") {echo "checked = checked";} ?>
name="checked[]" id="exclude" value= "exclude"><BR CLEAR="all">
<label>Override</label>
<input type="checkbox" <?php if ($gl_field['override'] == "TRUE") {echo "checked = checked";} ?>
name= "checked[]" id= "override" value = "override"/><BR CLEAR="all">
In Controller
public function update_table(){
$this->load->helper('form');
$this->page_nav_model->update_table();
$checked_array = $_POST['checked'];
$this->page_nav_model->update_checked($checked_array);
$this->load->view('pages/success');
}
In Model
foreach($checked_array as $true){
echo $true;
}
To clarify when I pull the information into the form in the example above all of the checkboxes are set to "TRUE" in the db so they are checked. If I uncheck stat and click submit I am able to see an array with the values (exclude, override).
I appreciate any help that sets me in the right direction.
To update your table with CI all at once, you need an array like this:
$data = array(
'column_1_name' => 'value_to_insert'
'column_2_name' => 'value_to_insert'
'column_2_name' => 'value_to_insert'
);
Right now, you have an array like this $checked_array = ('stat', 'exclude', 'override') - with more or fewer members.
To create the array that you can use in your update statement (like $data above), what you need to do is create another array with the name of each column and a value equal to 1 if it is in $checked_array or 0 if it was not in $checked array.
The function add_values() below can do that for you. You have to supply two arguments:
$all_possibilities is an array of each column name that you will want to update to either 1 or 0. In this case, it should look like $all_possibilities = array('stat', 'exclude', 'override');
$selected: this is an array with the names of the boxes that were actually selected - it is a subset of $all_possibilities (or it is the same if all the boxes were checked).
This function goes in your controller.
function add_values($all_possibilities, $selected) {
$array_for_query = array();
// this goes through each possible box that can be checked to see if that possibility was actually selected
foreach($all_possibilities as $array_member) {
// this checks to see if the current member of $all_possibilities is found in the $selected array
if (in_array($array_member, $selected)) {
// if it is, it adds that as a member of a new query $array_for_query and gives it a value of 1 (true)
$array_for_query[$array_member] = 1;
} else {
// if it is not, same as above, but gives it a value of 0
$array_for_query[$array_member] = 0;
}
}
// once all the possibilities have been checked and added to the query array, that array is returned
return $array_for_query;
}
Now you can call the function and pass the two arguments in. The returned array is assigned to $checked_and_unchecked.
$data['checked_and_unchecked'] = add_values($possibilities, $checked_array);
Make sure you also grab the gl_id from the form. You can do that with a hidden field in your view:
<input type="hidden" name="gl_id" value="<?php echo $gl_field['gl_id'];?>" />
In the controller, grab that value with
$data['gl_id'] = $this->input->post('gl_id');
Then you can pass the information to your model and update your table passing in the name of the table and the array you created.
$this->model_name->model_method($data);
This will then go in the model:
$this->db->update('table_name', $checked_and_unchecked);
$this->db->where('gl_id', $gl_id);
If a checkbox is unchecked in the HTML, the value does not get sent via $_POST. This is not accounted for in CodeIgniter. This is how I deal with this issue. In the controller:
/**
* Set post values for unchecked boxes.
*
* #access private
* #return void
*/
private function _section_checkboxes()
{
if (!$this->input->post('is_active')) {$_POST['is_active'] = 0;}
// other checkboxes here...
}
/**
* if form validation passes, run this to edit a section
*
* #access public
* #return void
*/
public function do_edit_section()
{
$this->_section_checkboxes();
if ($this->section_model->edit_section($this->input->post()))
{
redirect('success_page');
}
}
And in the model:
/**
* updates a section with active record, returns success.
*
* #access public
* #param array $data
* #return bool
*/
public function edit_section(array $data)
{
$this->db->where('id', $data['id']);
return $this->db->update('sections', $data);
}
And in the view, using the form helper:
<?=form_checkbox(array('name' => 'is_active', 'id' => 'is_active_field', 'value' => '1', 'checked' => (bool)$item->is_active))?>
Now your unchecked checkboxes are set as 0 when unchecked, 1 when checked. I hope this answers your question.
So I still needed help getting the final touches on the overall project so I wanted to post the final results here for anyone as green as I looking to control checkboxes from the db and the db from checkboxes.
Controller:
[function from Tayler and]
$all_checkbox_fields = array('stat','exclude','override');
$checked_array = $_POST['checkbox'];
$data['checkbox'] = $this->add_values($all_checkbox_fields, $checked_array);
$data['gl_id'] = $this->input->post('gl_id');
$this->page_nav_model->update_checked($data);
$this->load->view('pages/success');
Model:
public function update_checked($data){
$this->default_db->where('gl_id', $data['gl_id']);
$this->default_db->update('oracle_table', $data['checkbox']);
}
View:
<label>Stat</label>
<input type="checkbox" <?php if ($gl_field['stat'] == "1") {echo "checked = checked";} ?>
name = "checkbox[]" id="stat" value= "stat"/><BR>
<label>Exclude</label>
<input type="checkbox" <?php if ($gl_field['exclude'] == "1") {echo "checked = checked";} ?>
name="checkbox[]" id="exclude" value= "exclude"/><BR>
<label>Override</label>
<input type="checkbox" <?php if ($gl_field['override'] == "1") {echo "checked = checked";} ?>
name= "checkbox[]" id= "override" value = "override" ><BR>
I have this code in my controller (admin):
function save(){
$model = $this->getModel('mymodel');
if ($model->store($post)) {
$msg = JText::_( 'Yes!' );
} else {
$msg = JText::_( 'Error :(' );
}
$link = 'index.php?option=com_mycomponent&view=myview';
$this->setRedirect($link, $msg);
}
In model I have:
function store(){
$row =& $this->getTable();
$data = JRequest::get('post');
if(strlen($data['fl'])!=0){
return false;
}
[...]
And this is working - generate error message, but it return to items list view. I want to stay in edit view with entered data. How to do it?
In your controller you can:
if ($model->store($post)) {
$msg = JText::_( 'Yes!' );
} else {
// stores the data in your session
$app->setUserState('com_mycomponent.edit.mymodel.data', $validData);
// Redirect to the edit view
$msg = JText::_( 'Error :(' );
$this->setError('Save failed', $model->getError()));
$this->setMessage($this->getError(), 'error');
$this->setRedirect(JRoute::_('index.php?option=com_mycomponent&view=myview&id=XX'), false));
}
then, you will need to load the data from session with something like:
JFactory::getApplication()->getUserState('com_mycomponent.edit.mymodel.data', array());
normally this is loaded in the method "loadFormData" in your model. Where to load that data will depend on how are you implementing your component. If you are using the Joomla's form api then you can add the following method to your model.
protected function loadFormData()
{
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState('com_mycomponent.edit.mymodel.data', array());
if (empty($data)) {
$data = $this->getItem();
}
return $data;
}
EDIT:
BUT please note, that Joomla's API already can do all this for you if you controller inherits from "JControllerForm", you don't need to rewrite the save method. The best way to create your component is copying what is in Joomla's core components, com_content for example
It is not recommended to rewrite save or any method.
If you really want to override something and want to update something before or after save, you should use JTable file.
For Example:
/**
* Example table
*/
class HelloworldTableExample extends JTable
{
/**
* Method to store a node in the database table.
*
* #param boolean $updateNulls True to update fields even if they are null.
*
* #return boolean True on success.
*/
public function store($updateNulls = false)
{
// This change is before save
$this->name = str_replace(' ', '_', $this->name);
if (!parent::store($updateNulls))
{
return false;
}
// This function will be called after saving table
AnotherClass::functionIsCallingAfterSaving();
}
}
You can extends any method using JTable class and that's the recommended way to doing it.
I am trying to validate a form submission in Kohana 3. I have the form::open point to my action_create in my controller which successfully validates the data posted to it from the form in my view. If the data passes validation, a new item is created as intended, and the user is redirected to the item that was just created. This works correctly. If the data fails validation, however, I would like the user to be directed back to the originating view/page while retaining a variable containing the data that was posted so that I can repopulate the form and display errors.
In short, how can I pass data from a view -> controller -> original view?
Thank you, everyone!
The user also posed this question on the Kohana forums.
Those seeking an answer to this should have look over there.
I assume you're using Controller_Template.
File views/form.php:
// Set default variables if variables not passed to this view
$username = isset($username) ? $username : '';
echo Form::open('login');
// Input: username
echo Form::label('username', 'Username');
echo Form::input('username', $username);
echo isset($errors['username']) ? $errors['username'] : '';
// Input: username
echo Form::label('password', 'Password');
echo Form::input('password', $password);
echo isset($errors['password']) ? $errors['password'] : '';
echo Form::close();
File views/template.php
<html>
<head><title>My Website</title></head>
<body>
<?php echo isset($content) ? $content : ''; ?>
</body>
</html>
File classes/controller/user.php
Class Controller_User extends Controller_Template {
public $template = 'template';
public function index()
{
$this->template->content = $this->display_form('form');
}
public function login()
{
// Setup validation & rules here
// Check validation, assume $validation is Validation object
if ($validation->check()
{
// Validation succeeded. Do anything you want here
}
else
{
// Validation failed. Display form with entered values
$form_vars = $_POST;
$form_vars['errors'] = $validation->errors();
// Display form
$this->template->content = $this->display_form('form', $form_vars);
}
}
// Displaying form
private function display_form($form_file, $form_vars=NULL)
{
$form = View::factory($form_file);
if ($form_vars != NULL)
{
foreach($form_vars as $key => $value)
{
$form->$key = $value;
}
}
return $form;
}
}
Hope that helps!