Joomla - Where to edit the insert SQL? - php

I'm learning to create MVC component right now. I studied the code that was created using the component creator.
Now I wanna to locate the SQL insert function after the save button is click in the edit form, where does the form send to to call the insert function?
com_astock/admin/view/addstock/tmpl/edit.php
<?php
/**
* #version 1.0.0
* #package com_astock
* #copyright Copyright (C) 2013. All rights reserved.
* #license GNU General Public License version 2 or later; see LICENSE.txt
* #author Joe <joequah1#hotmail.com> - http://
*/
// no direct access
defined('_JEXEC') or die;
JHtml::addIncludePath(JPATH_COMPONENT . '/helpers/html');
JHtml::_('behavior.tooltip');
JHtml::_('behavior.formvalidation');
JHtml::_('formbehavior.chosen', 'select');
JHtml::_('behavior.keepalive');
// Import CSS
$document = JFactory::getDocument();
$document->addStyleSheet('components/com_astock/assets/css/astock.css');
?>
<script type="text/javascript">
js = jQuery.noConflict();
js(document).ready(function(){
});
Joomla.submitbutton = function(task)
{
if(task == 'addstock.cancel'){
Joomla.submitform(task, document.getElementById('addstock-form'));
}
else{
if (task != 'addstock.cancel' && document.formvalidator.isValid(document.id('addstock-form'))) {
Joomla.submitform(task, document.getElementById('addstock-form'));
}
else {
alert('<?php echo $this->escape(JText::_('JGLOBAL_VALIDATION_FORM_FAILED')); ?>');
}
}
}
</script>
<form action="<?php echo JRoute::_('index.php?option=com_astock&layout=edit&stock_code=' . (int) $this->form->getInput('stock_code')); ?>" method="post" enctype="multipart/form-data" name="adminForm" id="addstock-form" class="form-validate">
<div class="row-fluid">
<div class="span10 form-horizontal">
<fieldset class="adminform">
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('stock_code'); ?></div>
<div class="controls"><?php echo $this->form->getInput('stock_code'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('name'); ?></div>
<div class="controls"><?php echo $this->form->getInput('name'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('state'); ?></div>
<div class="controls"><?php echo $this->form->getInput('state'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('time_created'); ?></div>
<div class="controls"><?php echo $this->form->getInput('time_created'); ?></div>
</div>
<div class="control-group">
<div class="control-label"><?php echo $this->form->getLabel('created_by'); ?></div>
<div class="controls"><?php echo $this->form->getInput('created_by'); ?></div>
</div>
</fieldset>
</div>
<input type="hidden" name="task" value="" />
<?php echo JHtml::_('form.token'); ?>
</div>
</form>
if the html the action is index.php/view=addstock&layout=edit
Where does the layout edit call to? I had try to locate my entire component I couldn't find any insert SQL.
I will be showing my index.html.php as well
<?php
/**
* #version 1.0.0
* #package com_astock
* #copyright Copyright (C) 2013. All rights reserved.
* #license GNU General Public License version 2 or later; see LICENSE.txt
* #author Joe <joequah1#hotmail.com> - http://
*/
// No direct access
defined('_JEXEC') or die;
jimport('joomla.application.component.view');
/**
* View to edit
*/
class AStockViewAddstock extends JViewLegacy
{
protected $state;
protected $item;
protected $form;
/**
* Display the view
*/
public function display($tpl = null)
{
$this->state = $this->get('State');
$this->item = $this->get('Item');
$this->form = $this->get('Form');
// Check for errors.
if (count($errors = $this->get('Errors'))) {
throw new Exception(implode("\n", $errors));
}
$this->addToolbar();
parent::display($tpl);
}
/**
* Add the page title and toolbar.
*/
protected function addToolbar()
{
JFactory::getApplication()->input->set('hidemainmenu', true);
$user = JFactory::getUser();
$isNew = ($this->item->stock_code == 0);
if (isset($this->item->checked_out)) {
$checkedOut = !($this->item->checked_out == 0 || $this->item->checked_out == $user->get('stock_code'));
} else {
$checkedOut = false;
}
$canDo = AStockHelper::getActions();
JToolBarHelper::title(JText::_('COM_ASTOCK_TITLE_STOCK'), 'addstock.png');
// If not checked out, can save the item.
if (!$checkedOut && ($canDo->get('core.edit')||($canDo->get('core.create'))))
{
JToolBarHelper::apply('addstock.apply', 'JTOOLBAR_APPLY');
JToolBarHelper::save('addstock.save', 'JTOOLBAR_SAVE');
}
if (!$checkedOut && ($canDo->get('core.create'))){
JToolBarHelper::custom('addstock.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false);
}
// If an existing item, can save to a copy.
if (!$isNew && $canDo->get('core.create')) {
JToolBarHelper::custom('addstock.save2copy', 'save-copy.png', 'save-copy_f2.png', 'JTOOLBAR_SAVE_AS_COPY', false);
}
if (empty($this->item->stock_code)) {
JToolBarHelper::cancel('addstock.cancel', 'JTOOLBAR_CANCEL');
}
else {
JToolBarHelper::cancel('addstock.cancel', 'JTOOLBAR_CLOSE');
}
}
}

You cannot see save code as your controller and model extends parent classes.
You can create your own public function save in controller and model or override it.
Basically this is how it works:
Controller method 'Save' is called, which validates data and loads model.
Controller calls Model and pass him valid data.
Model loads JTable, which stores the data and returns true or false
Model returns bool to controller
Controller handles redirect
Classes are located in:
libraries/legacy/controller and libraries/legacy/model

Try to create your component using the Component Creator and see how it does it. It can be a great leaning tool.

simple presave hook:
go to your model and write:
public function save($data){
// do stuff with $data
return parent::save($data);
}
better would be using the prepareTable function:
protected function prepareTable($table)
{
$table->fieldname = 'new_value';
}

Related

How to call a function within a class method property?

I am trying to call an external function within a class method property. It actually does gets called but at the end of the page and whatever is inside the method property, remains separate.
Since I am a self taught student, it is recent that I have started learning PHP classes so I am not really sure if this can be done or not.
Please guide me how this can be done correctly or if not, then what could be the workaround?
The class I have written is as follows:
It will take the input from user while creating of instance and render a modal box based on the input and options selected.
class modalBox{
private $modal_id, $modal_anim, $header_title, $modal_content,$footer;
private $headerOpt,$titleOpt,$footerOpt,$closeBtn;
public function setID($id){
$this->modal_id = $id;
}
public function getID(){
$modal_id = $this->modal_id;
return $modal_id;
}
public function setTitle($title){
$this->header_title = $title;
}
public function getTitle(){
$title = $this->header_title;
return $title;
}
public function setBodyContent($content){
$this->modal_content = $content;
}
public function getBodyContent(){
$modalContent = $this->modal_content;
return $modalContent;
}
public function setFooterContent($footer){
$this->footer = $footer;
}
public function getFooterContent(){
$footerContent = $this->footer;
return $footerContent;
}
public function initiateModal($modal_anim, $headerOpt, $titleOpt, $closeX, $footerOpt, $footerCloseBtn){ ?>
<div class="modal <?php if($modal_anim != 'false'){echo $modal_anim;} ?>" id="<?php echo $this->getID(); ?>" style="z-index: 2;">
<div class='modal-dialog'>
<div class='modal-content'>
<?php
// display if header option is set to true
if ($headerOpt){
?>
<div class="modal-header">
<h4><?php echo $this->getTitle(); ?></h4>
<?php
// display if close button (X) is set to true
if($closeX){
?> <button type="button" class="close" data-dismiss="modal">×</button> <?php } ?>
</div>
<?php } ?>
<div class="modal-body"><?php echo $this->getBodyContent(); ?></div>
<?php if($footerOpt){ ?>
<div class="modal-footer"><?php echo $this->getFooterContent(); ?>
<?php if($footerCloseBtn){ ?>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<?php } ?>
</div>
<?php } ?>
</div>
</div>
</div>
<?php
}
}
?>
The function I am trying to call within property is as follows;
This function is not inside a class. This is present independently in functions.php which I have included in index file.
function getDocNameList() {
global $db;
$getDoc = $db->prepare("SELECT id,doc_name from doctor");
$getDoc->execute();
while($docName = $getDoc->fetch(PDO::FETCH_ASSOC)){
// print the returned rows in options list of <select>
echo "<option value='".$docName['id']."'>".$docName['doc_name']."</option>";
}
}
The initiation of class instance is as follows, Please note where I am calling the function
// create class instance
$rangeModal = new modalBox;
//set the modal id
$rangeModal->setID ("rangeFields");
//set the modal title in header
$rangeModal->setTitle("Select Date Range");
// set the body content
$rangeModal->setBodyContent("
<form method='post' action='expenditure.php'>
<div role='wrapper' class='input-group mb-3'>
<input id='datepicker1' name='exp_date_from' value='From Date' required/>
</div>
<div role='wrapper' class='input-group mb-3'>
<input id='datepicker2' name='exp_date_to' value='To Date' required/>
</div>
<div role='wrapper' class='input-group mb-3'>
<select>" . getDocNameList() . "</select>
</div>
");
//set the footer content
$rangeModal->setFooterContent("
<input type='submit' class='btn btn-success' name='submitRange' />
</form>
");
/*
* #args ---
* modal animation
* modal header (boolean)
* modal title (boolean)
* modal close X (boolean)
* modal footer (boolean)
* modal footer close button (boolean)
*/
// initiate modal
$rangeModal->initiateModal('fade',true,true,true,true,true);
I expect the output of the function to be displayed as .... within the block but instead it gets rendered at the bottom of the page just before tag.
You echo it here, so it will be displayed immediately:
echo "<option value='".$docName['id']."'>".$docName['doc_name']."</option>";
So it is not concatenated here, the function does not return anything:
<select>" . getDocNameList() . "</select>
Build it and return it instead:
$output = '';
while($docName = $getDoc->fetch(PDO::FETCH_ASSOC)){
$output .= "<option value='".$docName['id']."'>".$docName['doc_name']."</option>";
}
return $output;
Or build an array and join the elements:
while($docName = $getDoc->fetch(PDO::FETCH_ASSOC)){
$output[] = "<option value='".$docName['id']."'>".$docName['doc_name']."</option>";
}
return implode($output);

csv file data upload to mysql in codeigniter Invalid argument supplied for foreach() and Undefined variable: result

Am uploading csv data to mysql database ,while uploading getting below errors, Please find my controller and library and view file
Controller is csv.php
<?php
class Csv extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('csv_model');
$this->load->library('csvimport');
}
function index() {
$data['addressbook'] = $this->csv_model->get_addressbook();
$this->load->view('csvindex', $data);
}
function importcsv() {
$data['addressbook'] = $this->csv_model->get_addressbook();
$data['error'] = ''; //initialize image upload error array to empty
$config['upload_path'] = './uploads/';
$config['allowed_types'] = '*';
$config['max_size'] = 1000;
$this->load->library('upload', $config);
// If upload failed, display error
if (!$this->upload->do_upload('userfile')) {
$data['error'] = $this->upload->display_errors();
$this->load->view('csvindex', $data);
} else {
$file_data = $this->upload->data();
$file_path = './uploads/'.$file_data['file_name'];
if ($this->csvimport->get_array($file_path)) {
$csv_array = $this->csvimport->get_array($file_path);
foreach ($csv_array as $row) {
$insert_data = array(
'firstname'=>$row['firstname'],
'lastname'=>$row['lastname'],
'phone'=>$row['phone'],
'email'=>$row['email'],
);
$this->csv_model->insert_csv($insert_data);
}
$this->session->set_flashdata('success', 'Csv Data Imported Succesfully');
redirect(base_url().'csv');
//echo "<pre>"; print_r($insert_data);
} else
$data['error'] = "Error occured";
$this->load->view('csvindex', $data);
}
}
}
/*END OF FILE*/
library file is csvimport.php added in libraries
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter CSV Import Class
*
* This library will help import a CSV file into
* an associative array.
*
* This library treats the first row of a CSV file
* as a column header row.
*
*
* #package CodeIgniter
* #subpackage Libraries
* #category Libraries
* #author Brad Stinson
*/
class Csvimport {
private $filepath = "";
private $handle = "";
private $column_headers = "";
/**
* Function that parses a CSV file and returns results
* as an array.
*
* #access public
* #param filepath string Location of the CSV file
* #param column_headers array Alternate values that will be used for array keys instead of first line of CSV
* #param detect_line_endings boolean When true sets the php INI settings to allow script to detect line endings. Needed for CSV files created on Macs.
* #return array
*/
public function get_array($filepath='', $column_headers='', $detect_line_endings=FALSE)
{
// If true, auto detect row endings
if($detect_line_endings){
ini_set("auto_detect_line_endings", TRUE);
}
// If file exists, set filepath
if(file_exists($filepath))
{
$this->_set_filepath($filepath);
}
else
{
return FALSE;
}
// If column headers provided, set them
$this->_set_column_headers($column_headers);
// Open the CSV for reading
$this->_get_handle();
$row = 0;
while (($data = fgetcsv($this->handle, 0, ",")) !== FALSE)
{
// If first row, parse for column_headers
if($row == 0)
{
// If column_headers already provided, use them
if($this->column_headers)
{
foreach ($this->column_headers as $key => $value)
{
$column_headers[$key] = trim($value);
}
}
else // Parse first row for column_headers to use
{
foreach ($data as $key => $value)
{
$column_headers[$key] = trim($value);
}
}
}
else
{
$new_row = $row - 1; // needed so that the returned array starts at 0 instead of 1
foreach($column_headers as $key => $value) // assumes there are as many columns as their are title columns
{
$result[$new_row][$value] = trim($data[$key]);
}
}
$row++;
}
$this->_close_csv();
return $result;
}
/**
* Sets the filepath of a given CSV file
*
* #access private
* #param filepath string Location of the CSV file
* #return void
*/
private function _set_filepath($filepath)
{
$this->filepath = $filepath;
}
/**
* Sets the alternate column headers that will be used when creating the array
*
* #access private
* #param column_headers array Alternate column_headers that will be used instead of first line of CSV
* #return void
*/
private function _set_column_headers($column_headers='')
{
if(is_array($column_headers) && !empty($column_headers))
{
$this->column_headers = $column_headers;
}
}
/**
* Opens the CSV file for parsing
*
* #access private
* #return void
*/
private function _get_handle()
{
$this->handle = fopen($this->filepath, "r");
}
/**
* Closes the CSV file when complete
*
* #access private
* #return array
*/
private function _close_csv()
{
fclose($this->handle);
}
}
csv_model.php is below
<?php
class Csv_model extends CI_Model {
function __construct() {
parent::__construct();
}
function get_addressbook() {
$query = $this->db->get('addressbook');
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return FALSE;
}
}
function insert_csv($data) {
$this->db->insert('addressbook', $data);
}
}
/*END OF FILE*/
view file is csvindex.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Adddress Book Project</title>
<link href="<?php echo base_url(); ?>assets/bootstrap/css/bootstrap.css" type="text/css" rel="stylesheet" />
<link href="<?php echo base_url(); ?>assets/css/styles.css" type="text/css" rel="stylesheet" />
<script src="<?php echo base_url(); ?>assets/js/jquery.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">My Address book</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><i class="icon-home"></i>Home</li>
<li>About</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container" style="margin-top:50px">
<br>
<?php if (isset($error)): ?>
<div class="alert alert-error"><?php echo $error; ?></div>
<?php endif; ?>
<?php if ($this->session->flashdata('success') == TRUE): ?>
<div class="alert alert-success"><?php echo $this->session->flashdata('success'); ?></div>
<?php endif; ?>
<h2>CI Addressbook Import</h2>
<form method="post" action="<?php echo base_url() ?>csv/importcsv" enctype="multipart/form-data">
<input type="file" name="userfile" ><br><br>
<input type="submit" name="submit" value="UPLOAD" class="btn btn-primary">
</form>
<br><br>
<table class="table table-striped table-hover table-bordered">
<caption>Address Book List</caption>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Phone</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<?php if ($addressbook == FALSE): ?>
<tr><td colspan="4">There are currently No Addresses</td></tr>
<?php else: ?>
<?php foreach ($addressbook as $row): ?>
<tr>
<td><?php echo $row['firstname']; ?></td>
<td><?php echo $row['lastname']; ?></td>
<td><?php echo $row['phone']; ?></td>
<td><?php echo $row['email']; ?></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
<hr>
<footer>
<p>©My Address Book</p>
</footer>
</div>
</body>
</html>
when am trying to upload csv file am getting below errors, can any one please tell me where is the issue in my code, am trying last day onwards not getting result.Am downloaded code form this website please check..
This is link
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: libraries/csvimport.php
Line Number: 85
Backtrace:
File: C:\xampp\htdocs\niranjan\application\libraries\csvimport.php
Line: 85
Function: _error_handler
File: C:\xampp\htdocs\niranjan\application\controllers\csv.php
Line: 41
Function: get_array
File: C:\xampp\htdocs\niranjan\index.php
Line: 315
Function: require_once
Update the library csvimport.php to:
public function get_array($filepath='', $column_headers=array(), $detect_line_endings=FALSE)
{
...
}
Change the type of $column_headers parameter to an empty array instead of an empty single valued variable. It works!

Opencart template doesn't render

I just started learning OpenCart, currently using version 2.3.0.2 .
I created a module, everything works fine on the backend.
On the frontend however, when I return the template from the controller it shows up blank.
But if I add a die(); in the template it loads the template.
Controller code:
<?php
class ControllerExtensionModuleHelloworld extends Controller {
public function index() {
$this->load->language('extension/module/helloworld');
$data['heading_title'] = $this->language->get('heading_title');
$data['helloworld_value'] = html_entity_decode($this->config->get('helloworld_text_field'));
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/extension/module/helloworld.tpl')) {
// print_r(__LINE__);
return $this->load->view($this->config->get('config_template') . '/template/extension/module/helloworld.tpl', $data);
} else {
// print_r(__LINE__);
return $this->load->view('extension/module/helloworld.tpl');
}
}
}
Template code:
<div class="panel panel-default">
<div class="panel-heading"> <?php echo $heading_title; ?> </div>
<div class="panel-content" style="text-align: center;"> <?php echo $helloworld_value; ?> </div>
<div style="height:100px;width:100px;background-color:blue;"></div>
</div>
Fixed it by changing:
return $this->load->view('extension/module/helloworld.tpl', $data);
To:
$this->response->setOutput($this->load->view('extension/module/helloworld.tpl', $data));

redirect() function doesn't work

I have create a web application using CodeIgniter making at first a login interface. Here are the controller I used but I think something doesn't work but I don't know what.The home page, where the user is granted, it doesn't show.Unfortunately I didn't have a debugger to check what doesn't work. maybe there is a problem to handle the session but really I don't know what can be. maybe you are smarther than me to find the error
Login Controller
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('User','user'); /* This call the model to retrieve data from db */
}
public function index()
{
if(!file_exists('application/views/_login.php'))
{
show_404();
}
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<h4 style="text-align:center;">','</h4>');
$this->form_validation->set_rules('username','username','trim|required|xss_clean');
$this->form_validation->set_rules('password','password','trim|required|xss_clean|callback_pass_check');
if($this->form_validation->run() == FALSE)
{
/* Data to pass to view */
$data['title'] = "User Access";
$data['author'] = "Salvatore Mazzarino";
$data['year'] = date('Y');
$this->load->view('templates/_header',$data);
$this->load->view('_login',$data);
$this->load->view('templates/_footer',$data);
}
else
{
redirect('home', 'refresh');
}
}
public function pass_check($pass)
{
$result = $this->user->find_user($this->input->post('username'),$pass);
if(!empty($result))
{
foreach ($result as $row)
{
$session_array = array('id'=> $row->id, 'username'=> $row->username); /* Create a session passing user data */
$this->session->set_userdata('logged_in', $session_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('pass_check',"Invalid username or password!</br>Try again, please!");
return FALSE;
}
}
}
/* END OF FILE */
Home Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller
{
public function __construct()
{
parent::__construct();
session_start();
}
public function index()
{
if($this->session->userdata('logged_in'))
{
$data['title'] = "Management Emergency";
$data['author'] = "Salvatore Mazzarino";
$data['year'] = date('Y');
$this->load->view('templates/_header', $data);
$this->load->view('_home',$data);
$this->load->view('templates/_footer',$data);
}
else
{
redirect('login', 'refresh');
}
}
public function logout()
{
$this->session->unset_userdata('logged_in');
session_destroy();
redirect('home','refresh');
}
}
/* END OF FILE */
The model in the login controller works very well so It isn't a problem of query. Before adding session everything works but when I added session stopped to worked so I think that can be a problem or redirect() or session
Home View
<div data-role = "page">
<div data-role = "header" data-position = "inline">
<?php echo heading($title,1) ?>
</div>
<div class = "menu-content">
<ul data-role = "listview" data-inset="true">
<li data-role = "list-divider">Emergency Menù</li>
<li class = "menu-item">
<a href="">
<div class = "image-wrapper">
<img src="/assets/images/user.png" class = "ui-li-icons" />
</div>
Add patient
</a>
</li>
<li class = "menu-item">
<a href="#">
<div class = "image-wrapper">
<img src="/assets/images/home.png" class = "ui-li-icons" />
</div>
Show all hospital
</a>
</li>
<li class = "menu-item">
<a href="#">
<div class = "image-wrapper">
<img src="/assets/images/favorite.png" class="ui-li-icons" />
</div>
Find patients
</a>
</li>
<li class="menu-item">
<a href="#">
<div class = "image-wrapper">
<img src="/assets/images/email.png" class="ui-li-icons" />
</div>
Send medical infos
</a>
</li>
</ul>
Login View
<div data-role ="dialog">
<div data-role = "header" data-theme="e">
<?php echo heading($title,1) ?>
</div>
<div data-role ="content">
<?php
$var = validation_errors();
if(!empty($var))
{
echo form_error('username');
echo form_error('password');
}
else
{
echo heading('911 - First Aid',2,'style="text-align:center; color:red;"');
echo form_open('login');
?>
<div data-role ="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="name" value="" placeholder="Username"/>
</div>
<div data-role ="fieldcontain" class="ui-hide-label">
<label for="password">Password</label>
<input type="password" name="password" id="password" value="" placeholder="Password"/>
</div>
<div data-role ="fieldcontain">
<input type="submit" value="Login" data-theme ="b"/>
</div>
</form>
<?
}
?>
There is a problem with CodeIgniter retaining it's session data after a redirect. Your if($this->session->userdata('logged_in')) in your home.php controller will evaluate false every time because the session is resetting. You could use the native php sessions to skip over this problem.
See: http://codeigniter.com/wiki/Native_session/. Good luck!
UPDATE
Apparently, this is only true of CodeIgniter 1.7.2 when used with IE6. It doesn't affect most browsers.
open the application/config/autoload.php file and add the 'url' in the helper array;
$autoload['helper'] = array('url');
i hope this will help you to fix the problem.

How do you write forms?

in your framework are there any automation to build forms?
For example let's say you have this array of fields:
$fields = array('name'=>array('type'=>'input',otherparams)
'desc'=>array('type'=>'textarea',otherparams)
);
based on fields you should make HTML like this:
<form>
Name: <input name="name" type="text">
Description: <textarea name="desc"></textarea>
//>Submit
</form>
Do you build your html by-hand or is there some sort of automation?
Thanks
I work with the Yii framework. The php generates the html automatically. You write some html by hand but it's for the views. The views also have dynamic php variables that change. The actually full html document is put together by calling a controller with the web address, that controller deciding what models if any it needs to apply to the form and what view to put the model in. Then it generates the html.
SiteController.php
<?php
class SiteController extends Controller
{
/**
* Declares class-based actions.
*/
public function actions()
{
return array(
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
// page action renders "static" pages stored under 'protected/views/site/pages'
// They can be accessed via: index.php?r=site/page&view=FileName
'page'=>array(
'class'=>'CViewAction',
),
);
}
/**
* This is the default 'index' action that is invoked
* when an action is not explicitly requested by users.
*/
public function actionIndex()
{
// renders the view file 'protected/views/site/index.php'
// using the default layout 'protected/views/layouts/main.php'
$this->render('index');
}
/**
* This is the action to handle external exceptions.
*/
public function actionError()
{
if($error=Yii::app()->errorHandler->error)
{
if(Yii::app()->request->isAjaxRequest)
echo $error['message'];
else
$this->render('error', $error);
}
}
/**
* Displays the contact page
*/
public function actionContact()
{
$model=new ContactForm;
if(isset($_POST['ContactForm']))
{
$model->attributes=$_POST['ContactForm'];
if($model->validate())
{
$headers="From: {$model->email}\r\nReply-To: {$model->email}";
mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
$this->refresh();
}
}
$this->render('contact',array('model'=>$model));
}
/**
* Displays the login page
*/
public function actionLogin()
{
$model=new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login())
$this->redirect(Yii::app()->user->returnUrl);
}
// display the login form
$this->render('login',array('model'=>$model));
}
/**
* Logs out the current user and redirect to homepage.
*/
public function actionLogout()
{
Yii::app()->user->logout();
$this->redirect(Yii::app()->homeUrl);
}
}
ContactForm.php = This is the model.
<?php
/**
* ContactForm class.
* ContactForm is the data structure for keeping
* contact form data. It is used by the 'contact' action of 'SiteController'.
*/
class ContactForm extends CFormModel
{
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
/**
* Declares the validation rules.
*/
public function rules()
{
return array(
// name, email, subject and body are required
array('name, email, subject, body', 'required'),
// email has to be a valid email address
array('email', 'email'),
// verifyCode needs to be entered correctly
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
);
}
/**
* Declares customized attribute labels.
* If not declared here, an attribute would have a label that is
* the same as its name with the first letter in upper case.
*/
public function attributeLabels()
{
return array(
'verifyCode'=>'Verification Code',
);
}
}
This is the view:
contact.php
<?php
$this->pageTitle=Yii::app()->name . ' - Contact Us';
$this->breadcrumbs=array(
'Contact',
);
?>
<h1>Contact Us</h1>
<?php if(Yii::app()->user->hasFlash('contact')): ?>
<div class="flash-success">
<?php echo Yii::app()->user->getFlash('contact'); ?>
</div>
<?php else: ?>
<p>
If you have business inquiries or other questions, please fill out the following form to contact us. Thank you.
</p>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm'); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'subject'); ?>
<?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>128)); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'body'); ?>
<?php echo $form->textArea($model,'body',array('rows'=>6, 'cols'=>50)); ?>
</div>
<?php if(CCaptcha::checkRequirements()): ?>
<div class="row">
<?php echo $form->labelEx($model,'verifyCode'); ?>
<div>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->textField($model,'verifyCode'); ?>
</div>
<div class="hint">Please enter the letters as they are shown in the image above.
<br/>Letters are not case-sensitive.</div>
</div>
<?php endif; ?>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
<?php endif; ?>
Going to the page: http://yoursite/index.php/contact/ activates the actionContact method in the SiteController. That grabs the posted contact information, puts it into a model, and then renders a view.
CodeIgniter allows you to build forms using the Form Helper, although I prefer to write the HTML myself.
try this(not tested)
<?php
$fields = array('name'=>array('type'=>'input',name='fname')
'desciprtion'=>array('type'=>'textarea',name='desc')
);
?>
<form name="myform" action="" method="post">
<?php
foreach($fields as $key=>$value)
{
echo "<label>$key</label>";
echo " <$key['type'] name=\"$key['name']\" id=\"$key['id']>\">
}
?>

Categories