I have hit a brick wall on my codeigniter project.
I can update my theme/template to database via select form in my settings. I can do that OK and the themes/templates show up OK in the select form.
But the $templates == $config_template not showing the current theme/template that is selected.
I am not to sure what to add for the controller part and the model to be able to make it display current theme/template from database as first one.
Here is what I have done so far.
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Settings extends MX_Controller {
public function index() {
$this->document->setTitle($this->lang->line('heading_title'));
$data['action'] = site_url('admin/settings');
$data['logout'] = site_url('admin/logout');
$data['home'] = site_url('admin/dashboard');
$data['cancel'] = site_url('admin/dashboard');
$this->load->model('admin/setting/model_setting_store');
$this->model_setting_store->config_template();
$data['templates'] = array();
$directories = glob(APPPATH . 'modules/catalog/views/theme/*', GLOB_ONLYDIR);
foreach ($directories as $directory) {
$data['templates'][] = basename($directory);
}
$this->load->library('form_validation');
$this->form_validation->set_rules('config_meta_title', 'Website Title');
$this->form_validation->set_rules('config_meta_description', 'Description');
$this->form_validation->set_rules('config_meta_keyword', 'Keywords');
$this->form_validation->set_rules('config_template', 'Template');
if ($this->form_validation->run() == FALSE) {
return $this->load->view('setting/settings', $data);
} else {
redirect('admin/dashboard');
}
}
}
Model
<?php
class Model_setting_store extends CI_Model {
function config_template() {
$data = array(
'setting_id' => "10",
'website_id' => "0",
'group' => "config",
'key' => "config_template",
'value' => $this->input->post('config_template')
);
$this->db->update('setting', $data);
}
}
View
<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" id="form-setting" class="form-horizontal">
<ul class="nav nav-tabs" role="tablist" id="myTab">
<li class="active"><?php echo $tab_general;?></li>
<li><?php echo $tab_store; ?></li>
<li><?php echo $tab_server; ?></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="tab-general"></div>
<div class="tab-pane" id="tab-store">
<div class="form-group">
<label class="col-sm-2 control-label" for="input-template"><?php echo $entry_template; ?></label>
<div class="col-sm-10">
<select name="config_template" id="input-template" class="form-control">
<?php foreach ($templates as $template) { ?>
<?php if ($template == $config_template) { ?>
<option value="<?php echo $template; ?>" selected="selected"><?php echo $template; ?></option>
<?php } else { ?>
<option value="<?php echo $template; ?>"><?php echo $template; ?></option>
<?php } ?>
<?php } ?>
</select>
</div>
</form>
Haven't exactly tested it out but you can try this out with set_select using the Form Helper.
<select name="config_template" id="input-template" class="form-control">
<?php foreach( $templates as $template ): ?>
<option value="<?php echo $template; ?>" <?php echo set_select('config_template', $template, $template == $config_template ? TRUE : FALSE); ?>><?php echo $template; ?></option>
<?php endforeach; ?>
</select>
Edit: I actually don't see where you've set $config_template exactly. I only see it referenced in the model as $data['value'] or what would be $value in the view.
Related
Here are the changes applied according to #daniel's Answer.
In \catalog\view\theme\default\template\extension\module\sibling_category.tpl
<div class="box box-with-categories">
<div class="box-heading check_2"><?php echo $heading_title; ?></div>
<div class="strip-line"></div>
<div class="box-content box-category">
<ul class="accordion" id="accordion-category">
<?php $i = 0; foreach ($categories as $category) { $i++; ?>
<li class="panel">
<?php if ($category['category_id'] == $category_id) { ?>
<?php echo $category['name']; ?>
<?php } else { ?>
<?php echo $category['name']; ?>
<?php } ?>
</li>
<?php } ?>
</ul>
</div>
</div>
\catalog\controller\extension\module\sibling_category.php
<!--Have changed the controller logic, like you said -->
And In \catalog\language\en-gb\extension\module\sibling_category.php
<?php
// Heading
$_['heading_title'] = 'Sibling Categories';
So, Now what to do for appearing on list -> inside Category Layout.
And is there any way we can do this in coding so this appear in product/category.tpl file, so we don't need to create all files in admin folder.
EDIT: I've rewritten this answer to make it simpler to follow.
Your best bet here is to create a new Module rather than including this in the template. There are two stages: creating admin files & creating front-end files.
FRONT END
Start by duplicating all the front-end files of the standard "Category" module which consist of the following files, rename them according to your own definition e.g. sibling_category wherever you have category:
\catalog\view\theme\default\template\extension\module\category.tpl
\catalog\controller\extension\module\category.php
\catalog\language\en-gb\extension\module\category.php
We don't need a model here as the model for this as the ModelCatalogCategory class has the desired ability already.
So now you need to change the controller logic, edit the newly created sibling_category.php controller file. What we're doing here is getting the current category data ($current_id & $current_category), extracting the Parent category's id (parent_id) and then getting all children of the parent_id aka "siblings"
<?php
class ControllerExtensionModuleSiblingCategory extends Controller {
public function index() {
$this->load->language('extension/module/category');
$data['heading_title'] = $this->language->get('heading_title');
if (isset($this->request->get['path'])) {
$parts = explode('_', (string)$this->request->get['path']);
} else {
$parts = array();
}
if (isset($parts[0])) {
$data['category_id'] = $parts[0];
} else {
$data['category_id'] = 0;
}
$this->load->model('catalog/category');
$this->load->model('catalog/product');
$data['categories'] = array();
$current_id = $parts[count($parts) - 1];
$current_category = $this->model_catalog_category->getCategory($current_id);
$siblings = $this->model_catalog_category->getCategories($current_category['parent_id']);
foreach ($siblings as $category) {
$data['sibling_categories'][] = array(
'category_id' => $category['category_id'],
'name' => $category['name'] ,
'href' => $this->url->link('product/category', 'path=' . $category['category_id'])
);
}
$data['current_id'] = $current_id;
return $this->load->view('extension/module/sibling_category', $data);
}
}
Here's the default OC template's category.tpl modules file adjusted (edit for your template file accordingly replacing "$category_id" with "$current_id":
<div class="list-group">
<?php foreach ($sibling_categories as $category) { ?>
<?php if ($category['category_id'] == $current_id) { ?>
<?php echo $category['name']; ?>
<?php if ($category['children']) { ?>
<?php foreach ($category['children'] as $child) { ?>
<?php if ($child['category_id'] == $child_id) { ?>
- <?php echo $child['name']; ?>
<?php } else { ?>
- <?php echo $child['name']; ?>
<?php } ?>
<?php } ?>
<?php } ?>
<?php } else { ?>
<?php echo $category['name']; ?>
<?php } ?>
<?php } ?>
</div>
ADMIN AREA
In order to manage the module in the admin area, you will need to duplicate the language file and create a controller and the view:
\admin\language\en-gb\extension\module\category.php
Create a new file in the path \admin\controller\extension\module\sibling_category.php and insert this code:
<?php
class ControllerExtensionModuleSiblingCategory extends Controller {
private $error = array();
public function index() {
$this->load->language('extension/module/sibling_category');
$this->document->setTitle($this->language->get('heading_title'));
$this->load->model('extension/module');
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
if (!isset($this->request->get['module_id'])) {
$this->model_extension_module->addModule('sibling_category', $this->request->post);
} else {
$this->model_extension_module->editModule($this->request->get['module_id'], $this->request->post);
}
$this->session->data['success'] = $this->language->get('text_success');
$this->response->redirect($this->url->link('extension/extension', 'token=' . $this->session->data['token'] . '&type=module', true));
}
$data['heading_title'] = $this->language->get('heading_title');
$data['text_edit'] = $this->language->get('text_edit');
$data['text_enabled'] = $this->language->get('text_enabled');
$data['text_disabled'] = $this->language->get('text_disabled');
$data['entry_status'] = $this->language->get('entry_status');
$data['button_save'] = $this->language->get('button_save');
$data['button_cancel'] = $this->language->get('button_cancel');
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], true)
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_extension'),
'href' => $this->url->link('extension/extension', 'token=' . $this->session->data['token'] . '&type=module', true)
);
if (!isset($this->request->get['module_id'])) {
$data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('extension/module/html', 'token=' . $this->session->data['token'], true)
);
} else {
$data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('extension/module/html', 'token=' . $this->session->data['token'] . '&module_id=' . $this->request->get['module_id'], true)
);
}
if (!isset($this->request->get['module_id'])) {
$data['action'] = $this->url->link('extension/module/sibling_category', 'token=' . $this->session->data['token'], true);
} else {
$data['action'] = $this->url->link('extension/module/sibling_category', 'token=' . $this->session->data['token'] . '&module_id=' . $this->request->get['module_id'], true);
}
$data['cancel'] = $this->url->link('extension/extension', 'token=' . $this->session->data['token'] . '&type=module', true);
if (isset($this->request->get['module_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
$module_info = $this->model_extension_module->getModule($this->request->get['module_id']);
}
if (isset($this->request->post['name'])) {
$data['name'] = $this->request->post['name'];
} elseif (!empty($module_info)) {
$data['name'] = $module_info['name'];
} else {
$data['name'] = '';
}
if (isset($this->request->post['module_description'])) {
$data['module_description'] = $this->request->post['module_description'];
} elseif (!empty($module_info)) {
$data['module_description'] = $module_info['module_description'];
} else {
$data['module_description'] = array();
}
$this->load->model('localisation/language');
$data['languages'] = $this->model_localisation_language->getLanguages();
if (isset($this->request->post['status'])) {
$data['status'] = $this->request->post['status'];
} elseif (!empty($module_info)) {
$data['status'] = $module_info['status'];
} else {
$data['status'] = '';
}
$data['header'] = $this->load->controller('common/header');
$data['column_left'] = $this->load->controller('common/column_left');
$data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('extension/module/sibling_category', $data));
}
protected function validate() {
if (!$this->user->hasPermission('modify', 'extension/module/category')) {
$this->error['warning'] = $this->language->get('error_permission');
}
return !$this->error;
}
}
Finally create the view file at the path \admin\view\template\extension\module\sibling_category.tpl and insert the following:
<?php echo $header; ?><?php echo $column_left; ?>
<div id="content">
<div class="page-header">
<div class="container-fluid">
<div class="pull-right">
<button type="submit" form="form-category" data-toggle="tooltip" title="<?php echo $button_save; ?>" class="btn btn-primary"><i class="fa fa-save"></i></button>
<i class="fa fa-reply"></i></div>
<h1><?php echo $heading_title; ?></h1>
<ul class="breadcrumb">
<?php foreach ($breadcrumbs as $breadcrumb) { ?>
<li><?php echo $breadcrumb['text']; ?></li>
<?php } ?>
</ul>
</div>
</div>
<div class="container-fluid">
<?php if ($error_warning) { ?>
<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> <?php echo $error_warning; ?>
<button type="button" class="close" data-dismiss="alert">×</button>
</div>
<?php } ?>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><i class="fa fa-pencil"></i> <?php echo $text_edit; ?></h3>
</div>
<div class="panel-body">
<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" id="form-html" class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label" for="input-status"><?php echo $entry_status; ?></label>
<div class="col-sm-10">
<input type="hidden" name="name" value="<?php echo $heading_title; ?>" id="input-name" class="form-control" />
<select name="status" id="input-status" class="form-control">
<?php if ($status) { ?>
<option value="1" selected="selected"><?php echo $text_enabled; ?></option>
<option value="0"><?php echo $text_disabled; ?></option>
<?php } else { ?>
<option value="1"><?php echo $text_enabled; ?></option>
<option value="0" selected="selected"><?php echo $text_disabled; ?></option>
<?php } ?>
</select>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<?php echo $footer; ?>
Once you've done this, you may need to update your admin permissions. Navigate to "Settings=>Users=>UserGroups" and edit your Admin user type. Make sure you either "Select All" for read and modify permission or select it manually.
You need to then "Install" this module and then edit it, set it to enabled and Save. You'll notice a "Sub-module" listed below the "Sibling Category" this is to get the module in the 'Layouts' page. Do not create multiple instances of the module as it may cause confusion on the layouts - unless you understand what you're doing.
NB When duplicating the language files, remember to find & replace all instances of "Category" with "Sibling Category"
How to retrieve the array values from multiples checkbox? I have problem when I retrieve value array and echo the value. I get this error
Severity: Warning
Message: in_array() expects parameter 2 to be array, string given
Filename: page/update.php.
Please, could you help me again? Thank you.
You find three files: View, Model and Controller. Please check where I wrong...
UPDATE.PHP:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<div class="row">
<div class="col-sm-12">
<?php echo form_open('page_controller/update_page_post'); ?>
<div class="form-group">
<div class="row">
<div class="col-sm-3 col-xs-12">
<label><?php echo trans('subcategory'); ?></label>
</div>
</div><div class="col-xm-12">
<div class="table-responsive">
<table class="table table-bordered table-striped" role="grid">
<tbody>
<tr>
<?php $valuesub = ($page->subcat_recip_id); ?>
<?php $array_of_values = explode(",", $valuesub);
//if ($item['parent_id'] != "0" && $item['subcat_recip_id'] == "0") :
foreach ($array_of_values as $item) {
if(in_array($valuesub,$item)): { ?>
<td>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>" CHECKED> <?php echo html_escape($item["title"]);
} ?>
<?php else: { ?>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>"> <?php echo html_escape($item["title"]);
}
endif; }?>
</td>
<?php echo html_escape($valuesub); ?></tr>
</tbody>
</table>
</div>
</div>
</div>
PAGE_CONTROLLER.PHP
public function update_page_post()
{
//validate inputs
$this->form_validation->set_rules('title', trans("title"), 'required|xss_clean|max_length[500]');
if ($this->form_validation->run() === false) {
$this->session->set_flashdata('errors', validation_errors());
$this->session->set_flashdata('form_data', $this->page_model->input_values());
redirect($this->agent->referrer());
} else {
//get id
$id = $this->input->post('id', true);
$redirect_url = $this->input->post('redirect_url', true);
if (!$this->page_model->check_page_name()) {
$this->session->set_flashdata('form_data', $this->page_model->input_values());
$this->session->set_flashdata('error', trans("msg_page_slug_error"));
redirect($this->agent->referrer());
exit();
}
if ($this->page_model->update($id)) {
$this->session->set_flashdata('success', trans("msg_updated"));
if (!empty($redirect_url)) {
redirect($redirect_url);
} else {
redirect(admin_url() . 'pages');
}
} else {
$this->session->set_flashdata('form_data', $this->page_model->input_values());
$this->session->set_flashdata('error', trans("msg_error"));
redirect($this->agent->referrer());
}
}
}
PAGE_MODEL.PHP
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Page_model extends CI_Model
{
//input values
public function input_values()
{
$checkbox = implode(',', $this->checkBox());
$data = array(
'lang_id' => $this->input->post('lang_id', true),
'title' => $this->input->post('title', true),
'slug' => $this->input->post('slug', true),
'page_description' => $this->input->post('page_description', true),
'page_keywords' => $this->input->post('page_keywords', true),
'page_content' => $this->input->post('page_content', false),
'page_order' => $this->input->post('page_order', true),
'parent_id' => $this->input->post('parent_id', true),
'page_active' => $this->input->post('page_active', true),
'title_active' => $this->input->post('title_active', true),
'breadcrumb_active' => $this->input->post('breadcrumb_active', true),
'right_column_active' => $this->input->post('right_column_active', true),
'need_auth' => $this->input->post('need_auth', true),
'howmany_people' => $this->input->post('howmany_people', true),
'difficulty' => $this->input->post('difficulty', true),
'howmany_time' => $this->input->post('howmany_time', true),
'location' => $this->input->post('location', true),
'subcat_recip_id' => $checkbox
);
return $data;
}
public function checkBox(){
$count = count($_POST['subcat_recip_id']);
for($n=0; $n<$count; $n++){
$checkbox[$n] = $_POST['subcat_recip_id'][$n];
}
return $checkbox;
}
//update page
public function update($id)
{
//set values
$data = $this->page_model->input_values();
if (empty($data["slug"])) {
//slug for title
$data["slug"] = str_slug($data["title"]);
if (empty($data["slug"])) {
$data["slug"] = "page-" . uniqid();
}
}
$page = $this->get_page_by_id($id);
if (!empty($page)) {
$this->db->where('id', $id);
return $this->db->update('pages', $data);
}
return false;
}
in your you view,
<tr>
<?php $valuesub = ($page->subcat_recip_id); ?>
<?php $array_of_values = explode(",", $valuesub);
foreach ($array_of_values as $item) {
if(in_array($subcat_recip_id,$item)): { ?>
<td>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>" CHECKED> <?php echo html_escape($item["title"]);
} ?>
<?php else: { ?>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>"> <?php echo html_escape($item["title"]);
}
endif; }?>
</td>
<?php echo html_escape($valuesub); ?>
</tr>
change to :
<tr>
<?php $valuesub = ($page->subcat_recip_id);
$array_of_values = explode(",", $valuesub); ?>
<td>
<?php foreach ($array_of_values as $item) :?>
<input type="checkbox" name="subcat_recip_id[]" class="square-purple" value="<?php echo html_escape($item["title"]); ?>" <?=(in_array($subcat_recip_id,$item))?"CHECKED":""?>> <?=html_escape($item["title"]);?>'
<?php endforeach; ?>
</td>
<?=html_escape($valuesub)?>
</tr>
in model :
public function update($id){
//set values
$data = $this->page_model->input_values();
if (empty($data["slug"])) {
//slug for title
$data["slug"] = str_slug($data["title"]);
if (empty($data["slug"])) {
$data["slug"] = "page-" . uniqid();
}
}
$page = $this->get_page_by_id($id);
if (!empty($page)) {
$this->db->where('id', $id);
return $this->db->update('pages', $data);
}
return false;
}
change to :
public function update($id){
$data = $this->input_values();
if (empty($data["slug"])) {
$data["slug"] = str_slug($data["title"]);
if (empty($data["slug"])) {
$data["slug"] = "page-" . uniqid();
}
}
$page = $this->get_page_by_id($id);
if (!empty($page)) {
$this->db->where('id', $id);
return $this->db->update('pages', $data);
}
return false;
}
please update if you getting error,
tq
Well, it remains a bug but with some changes yr last code works. The great problem is the loop, it re-load the $valuesub for how many times is the value. Ie. If the array is composed of three values, it reads three times the same value. Pls see the two screenshots: https://www.screencast.com/t/MfiEDhdFuX
I can't get this loop off !!
Code
<td>
<?php foreach ($menu_links as $item) :
$valuesub = ($page->subcat_recip_id);
$array_of_values = explode("," , $valuesub);
if ($item['parent_id'] != "0" && $item['subcat_recip_id'] == "0") :
foreach($array_of_values as $dt): ?>
<?php //if(in_array($dt,$item)): ?>
<input type="checkbox" name="subcat_recip_id" class="square-purple" value="<?php echo html_escape($item["title"]); ?>" <?=(in_array($dt,$item))?"CHECKED":""?>> <?=html_escape($item["title"]);?>
<?php endforeach; endif;?>
<?php endforeach; ?>
</td><?php echo html_escape($valuesub); ?>
Im trying to send 3 ids from 3 diferent tables and 1 varchar to a table called 'session', where it will save the ids and this varchar, my problem is, everytime i click to submit, it doesnt input anything to my table, and no error shows up..
VIEW
<link href='<?php echo site_url('assets/recursos/dashboard.css');?>' rel="stylesheet">
<div class="container">
<?php echo form_open('admin/inserirsessao'); ?>
<?php if (isset($message)) { ?>
<CENTER><h3 style="color:green;">Data inserted successfully</h3></CENTER><br>
<?php } ?>
<div class="col-xs-12">
<div class="form-group">
<label for="sel1">Filme</label>
<select name='filmes' class="form-control" id="filmes">
<?php
$id = $this->uri->segment(4);
$this->db->where('filme_id', $id);
$lista = $this->db->get('filme');
foreach($lista->result() as $row) {
?>
<option value="<?php echo $row->filme_id;?>"> <?php echo $row->Nome; ?></option>
<?php
}
?>
</select>
</div>
</div>
<h2 style="color:white; font-size:25px;">Adiciona um Filme<h2>
<div class="col-xs-12 ">
<div class="form-group">
<label for="sel1">Seleciona as Salas</label>
<select name='salas' class="form-control" id="salas">
<?php
$lista = $this->db->get('sala');
foreach($lista->result() as $row) {
?>
<option value="<?php echo $row->sala_id;?>" > <?php echo $row->description; ?></option>
<?php
}
?>
</select>
</div>
<div class="col-xs-12">
<div class="form-group">
<label for="sel1">Seleciona tipo de filme</label>
<select name="tipofilme" class="form-control" id="tipofilme">
<?php
$lista = $this->db->get('tipo_filme');
foreach($lista->result() as $row) {
?>
<option value="<?php echo $row->tipo_filme_id;?>"><?php echo $row->tipo_filme; ?></option>
<?php
}
?>
</select>
</div>
</div>
</div>
<div class="col-xs-12">
<p style="color:white" class="text-center">Insere Hora da Sessão</p>
<div class="separator">
<?php echo form_label('Hora:'); ?> <?php echo form_error('hora'); ?>
<?php echo form_input(array('id' => 'hora', 'name' => 'hora')); ?><br />
</div>
</div>
</ul>
</li>
<?php echo form_submit(array('id' => 'submit', 'value' => 'Submit')); ?> <br/>
<?php echo form_close(); ?><br/>
</div>
</div>
</div>
CONTROLLER
public function index()
{
$this->render('admin/inseresessao');
}
public function sessao()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
//Validating Name Field
$this->form_validation->set_rules('hora', 'Hora', 'required');
if ($this->form_validation->run() == FALSE) {
$this->render('admin/inserirsessao');
} else {
//Setting values for tabel columns
$dadossessao = array(
'hora' =>$this->input->post('hora'),
'sala_id'=>$this->input->post('salas'),
'tipo_filme_id'=>$this->input->post('tipofilme'),
'filme_id'=>$this->input->post('filmes')
);
//Transfering data to Model
$this->insert_model1->form_insert($dadossessao);
$dadosessao['message'] = 'Dados Foram Inseridos com Sucesso';
//Loading View
$this->render('admin/inserirsessao');
}
}
}
?>
MODEL
<?php
class insert_model1 extends CI_Model{
function __construct() {
parent::__construct();
}
function form_insert( $dadossessao){
$this->db->insert('session', $dadossessao);
return $dadossessao;
}
}
?>
I've been already hours trying to fix the problem but i don't know whats happening, can someone help me?
change your form action to <?php echo form_open('inserirsessao/sessao'); ?> .
I am developing a site with CI 2.1.3
I have a blog module, in this blog I have a form to post a comment.
I am calling this form inside a view with:
echo Modules:: run('blog/comment');
When I submit this form with ajaxForm, the values of the input fields are not being cleared.
My controller’s function for the comment form:
public function comment($postId)
{
$this->load->helper('form');
$this->data['success'] = FALSE;
$this->data['postId'] = $postId;
if(!isset($_POST['comment_submit']))
{
$this->data['new_comment'] = $this->blog_comment_m->get_new();
}
else
{
$this->data['new_comment'] = $this->blog_comment_m->object_from_post(array('author', 'authur_email', 'content'));
$this->load->library('form_validation');
$rules = $this->blog_comment_m->rules;
$this->form_validation->set_rules($rules);
if($this->form_validation->run() == TRUE)
{
$this->data['success'] = TRUE;
$this->data['new_comment'] = $this->blog_comment_m->get_new();
}
}
$this->load->view('add_comment', $this->data);
}
The comment form:
<div id="commentAjax">
<?php $attr = array('id'=>'commentForm'); echo form_open(site_url('blog/comment/' .
$postId), $attr); ?>
<input type="hidden" name="post_id" value="<?php echo $postId; ?>" />
<div style="border-top:2px groove #930"><h4>Leave a Comment</h4></div>
<div class="control-group <?php if(form_error('author')) echo 'error'; ?>">
<label>Name *</label>
<?php echo form_input(array('name'=>'author', 'class'=>'input-large', 'value'=>set_value('author', $new_comment->author))); ?>
<span class="help-block"><?php echo form_error('author'); ?></span>
</div>
<div class="control-group <?php if(form_error('author_email')) echo 'error'; ?>">
<label>Email *</label>
<?php echo form_input(array('name'=>'author_email', 'class'=>'input-large', 'value'=>set_value('author_email', $new_comment->author_email))); ?>
<span class="help-block"><?php echo form_error('author_email'); ?></span>
</div>
<div class="control-group <?php if(form_error('content')) echo 'error'; ?>">
<label>Comment *</label>
<?php echo form_textarea(array('name'=>'content', 'value'=>set_value('content', $new_comment->content))); ?>
<span class="help-block"><?php echo form_error('content'); ?></span>
</div>
<div>
<?php echo form_submit('submit', 'Send Comment', 'class="btn btn-submit"');?>
<input type="hidden" name="comment_submit" value="1" />
</div>
<?php echo form_close(); ?>
<?php if($success): ?>
<div style="border:1px solid #666; background:#9F9; color:#000; margin-top:10px; width:50%; padding:5px; font-weight:bold">
<p>Thank you for your comment.</p>
<p>To avoid spam, your comment has been submitted for approval.</p>
<p><h2 class="highland">Highland Coffee Roastery</h2></p>
</div>
<?php endif; ?>
</div>
<script>
$(function()
{
var options = { target: '#commentAjax' };
$('#commentForm').ajaxForm(options);
});
</script>
I dumped the $new_comment array and the fields values are empty.
I checked the page source and the input fields values = ''.
Yet, I still see the values that I submitted in the input fields.
Refreshing the page, still, displays the values.
What is wrong?
I got the answer on the Daniweb forum:
Ok, the problem is that set_value() doesn’t consider if the validation runs true or false, usually you redirect() and so the POST array is resetted automatically, here we can force this action by extending /system/libraries/Form_validation.php, create /application/libraries/MY_Form_validation.php and paste this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class My_Form_validation extends CI_Form_validation {
public function __construct()
{
parent::__construct();
}
public function resetpostdata()
{
$obj =& _get_validation_object();
foreach($obj->_field_data as $key)
{
$this->_field_data[$key['field']]['postdata'] = NULL;
}
return true;
}
}
?>
After the validation runs true, call the method, as in this example:
if($this->form_validation->run() === FALSE)
{
# . . .
}
else
{
$this->form_validation->resetpostdata();
# load view & other stuff
}
I have created a class, it store the data from mySQL database into class.
The performance is really slow when outputting to the browser, I have to wait like 10 seconds and this is not acceptable. How to solve this problem?
In the controller file:
$modelCategory = new modelCategory();
$categories = $modelCategory->findAll('takeawayID = :id', array('id' => $takeawayID));
if ($categories === false) {
echo "Query failed";
return;
}
$data['categories'] = $categories;
View File:
<?php foreach ($categories as $category): ?>
<div class="menu-container">
<h2><?php echo $category->name; ?></h2>
<ul class="menu-list">
<?php foreach ($category->item as $item): ?>
<li class="<?php echo $class; ?>">
<div class="menu-holder">
<div class="text-block">
<div class="text-holder">
<?php if ($item->optionsTotal == 1): ?>
<?php foreach($item->options as $option): ?>
<?php $price = $option->price; ?>
<?php $optionvalue = $option->optionValue; ?>
<?php endforeach; ?>
<?php endif; ?>
<h3>
<?php echo $item->name; ?>
<?php if ($item->optionsTotal == 1 && $optionvalue != "Regular"): ?>
(<?php echo $optionvalue; ?>)
<?php endif; ?>
</h3>
<?php if ($item->desc != ""): ?>
<p> <?php echo $item->desc; ?> </p>
<?php endif; ?>
</div>
</div>
</div>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endforeach; ?>
model Category class file:
<?
class modelCategory extends Model {
public $id;
public $desc;
public $name;
public $items = null;
public function findAll($condition, $parameters) {
$query = "SELECT * FROM categories WHERE " . $condition;
$statement = self::getDb()->prepare($query);
if (!$statement->execute($parameters))
return false;
return self::createModels($statement->fetchAll());
}
public static function createModels($dataAr) {
$models = array();
foreach ($dataAr as $data) {
$category = new modelCategory;
$category->id = $data['id'];
$category->desc = $data['description'];
$category->name = ucwords(strtolower($data['name']));
$models[] = $category;
}
return $models;
}
public function getItems() {
if ($this->items === null)
$this->items = modelItem::find('category_id = :category_id', array('category_id' => $this->id));
return $this->items;
}
public function __get($key) {
switch ($key) {
case 'item':
return $this->getItems();
}
}
}
?>
modelItem:: class is very similar to model Category class.
one problem that I see is that you take the result and build a class to contain the data you could use PDO::FETCH_CLASS that does the same but in a more optimize way.
But like Michael J.V. said you should do some monitoring of your application to detect the exact cause of the problem (there might be multiple and not easy to catch with the eyes)