I am having trouble and since more than a week trying to find a solution to disallow duplicate form content if it is already exists in database.
So it will check all rows excluding the id (row) what currently I am editing and if same value exists it should give error message.
Here is my Code.
Position Controller
public function position_edit($id = NULL)
{
$this->data['title'] = '<i class="fa fa-user"></i> ' . lang('position_edit');
$this->data['position'] = $this->positions_model->get($id);
count($this->data['position']) || $this->data['errors'][] = 'position could not be found';
$id = $this->uri->segment(4);
$this->db->where('position', $this->input->post('position'));
!$id || $this->db->where('id !=', $id);
$pos = $this->positions_model->get();
echo '<pre>', print_r($pos), '</pre>';
if (count($pos) > 0) {
$this->form_validation->set_rules('position', 'lang:position_code', 'trim|required|max_length[10]|is_unique[positions.position]|xss_clean');
$this->form_validation->set_message('is_unique', lang('error_position_exists'));
}
if ($this->form_validation->run() === TRUE) {
$data = $this->positions_model->array_from_post(array('position', 'label'));
$this->positions_model->save($data, $id);
$this->session->set_flashdata('message', lang('position_record_updated'));
$this->data['message'] = $this->session->flashdata('message');
$this->session->set_flashdata('message_type', 'success');
$this->data['message_type'] = $this->session->flashdata('message_type');
//redirect('admin/hr/positions', 'refresh');
}
// Load the view
$this->load->view('hr/positions/edit', $this->data);
}
Position Model
class Positions_Model extends MY_Model
{
protected $_table_name = 'positions';
protected $_order_by = 'label ASC';
// This $rules currently not in use since it has been
// set directly to the controller edit method code
public $rules = array(
'position' => array(
'field' => 'position',
'label' => 'Position Code',
'rules' => 'trim|required|max_length[10]|xss_clean'
),
'label' => array(
'field' => 'label',
'label' => 'Position Label',
'rules' => 'trim|required|max_length[50]|xss_clean'
),
);
public function get_new()
{
$position = new stdClass();
$position->position = '';
$position->label = '';
return $position;
}
public function get_positions($id = NULL, $single = FALSE)
{
$this->db->get($this->_table_name);
return parent::get($id, $single);
}
public function get_positions_array($id = NULL, $single = FALSE)
{
$this->db->get($this->_table_name);
$positions = parent::get($id, $single);
$array = array();
foreach($positions as $pos){
$array[] = get_object_vars($pos);
}
return $array;
}
public function delete($id)
{
// Delete a position
parent::delete($id);
}
}
DB Model
class MY_Model extends CI_Model
{
protected $_table_name = '';
protected $_primary_key = 'id';
protected $_primary_filter = 'intval';
protected $_order_by = '';
public $rules = array();
protected $_timestamps = FALSE;
function __construct()
{
parent::__construct();
}
public function array_from_post($fields)
{
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
public function get($id = NULL, $single = FALSE)
{
if($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
} elseif($single == TRUE) {
$method = 'row';
} else {
$method = 'result';
}
if(!count($this->db->ar_orderby)) {
$this->db->Order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
public function get_by($where, $single = FALSE)
{
$this->db->where($where);
return $this->get(NULL, $single);
}
public function save($data, $id = NULL)
{
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
!isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
$this->db->set($data);
$this->db->insert($this->_table_name);
$id = $this->db->insert_id();
} else {
// Update
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
}
public function delete($id)
{
$filter = $this->_primary_filter;
$id = $filter($id);
if (!$id) {
return FALSE;
}
$this->db->where($this->_primary_key, $id);
$this->db->limit(1);
$this->db->delete($this->_table_name);
}
}
I have tried callback function also but it is not working at all and couldn't find what causing the issue.
EDIT:
Please note it The above code is giving message if I am inserting the value which already exists but it is not validating and storing the data if the row is not exists
Updated
if ($this->form_validation->run() === TRUE) {
//print_r($this->positions_model->unique_value('position', $this->uri->segment(4)));
if($this->positions_model->unique_value('position', $this->uri->segment(4))) {
$this->form_validation->set_message('unique_value', lang('error_position_exists'));
} else {
$data = $this->positions_model->array_from_post(array('position', 'label'));
$this->positions_model->save($data, $id);
$this->session->set_flashdata('message', lang('position_record_updated'));
$this->data['message'] = $this->session->flashdata('message');
$this->session->set_flashdata('message_type', 'success');
$this->data['message_type'] = $this->session->flashdata('message_type');
redirect('admin/hr/positions', 'refresh');
}
}
In Controller
public function unique_value($field, $id)
{
$id = $this->uri->segment(4);
$this->db->where($field, $this->input->post($field));
!$id || $this->db->where('id !=', $id);
$position = $this->positions_model->get();
if (count($position)) {
return TRUE;
}
return FALSE;
}
Please Note: I don't know what exactly happens to your code, but I wouldn't check between insert or update into the model, just in the controller
I would solve it using a checkExist Model function, that would check if all the values you want to check exists into the DDBB, and work according to it. I would also do it in the controller instead of the model. First, you validate the fields, and then you check if values exists excluding the edit id:
$values_from_post = $this->positions_model->array_from_post(array('position', 'label'));
// $editId is to avoid the id of the row you were editing
if ($this->form_validation->run() === TRUE ) {
if ( !$this->positions_model->check_duplicate( $values_from_post, $editId ) ) ){
// Insert Value
} else {
// Update Value
}
And in your model, you check the duplicate via a where if the values exists:
public function check_duplicate( $values_from_post, $editId ) {
foreach ( $values_from_post as $key => $value ) {
$this->db->where( $key, $value );
}
$this->db->where('id !=', $editId );
$result = $this->db->get($this->_table_name);
return ( ( $result->num_rows > 0 ) ? true : false );
}
Please, I didn't check the code, but that is the idea, instead of doing it in the model, control it in the controller and then insert or update depending of what happens.
Here is the default validation rule of CodeIgniter for checking the duplicate entries in two columns.
$this->form_validation->set_rules('form_field_name','Title here','required|max_length[255]|unique[table.table_column1,table.table_column2]');
Related
I'm a total newbie to Wordpress and having a hard time figuring things out.
I'm using plugin called "WP-Pro-Quiz", a quiz plugin, and within the plugin there's an option to show "Leaderboard" of all users who completed the quiz. In the leaderboard on the frontend, there's user id, time, points and user's Display Name, etc for each user..
What I want to achieve is to make Display name clickable (and then to go to author's profile once clicked). That is, to connect Display Name with author profile who took the quiz, to create hyperlink from Display Name.
This is from controller WpProQuiz_Controller_Toplist.php :
<?php
class WpProQuiz_Controller_Toplist extends WpProQuiz_Controller_Controller
{
public function route()
{
$quizId = $_GET['id'];
$action = isset($_GET['action']) ? $_GET['action'] : 'show';
switch ($action) {
default:
$this->showAdminToplist($quizId);
break;
}
}
private function showAdminToplist($quizId)
{
if (!current_user_can('wpProQuiz_toplist_edit')) {
wp_die(__('You do not have sufficient permissions to access this page.'));
}
$view = new WpProQuiz_View_AdminToplist();
$quizMapper = new WpProQuiz_Model_QuizMapper();
$quiz = $quizMapper->fetch($quizId);
$view->quiz = $quiz;
$view->show();
}
public function getAddToplist(WpProQuiz_Model_Quiz $quiz)
{
$userId = get_current_user_id();
if (!$quiz->isToplistActivated()) {
return null;
}
$data = array(
'userId' => $userId,
'token' => wp_create_nonce('wpProQuiz_toplist'),
'canAdd' => $this->preCheck($quiz->getToplistDataAddPermissions(), $userId),
);
if ($quiz->isToplistDataCaptcha() && $userId == 0) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
$data['captcha']['img'] = WPPROQUIZ_CAPTCHA_URL . '/' . $captcha->createImage();
$data['captcha']['code'] = $captcha->getPrefix();
}
}
return $data;
}
private function handleAddInToplist(WpProQuiz_Model_Quiz $quiz)
{
if (!wp_verify_nonce($this->_post['token'], 'wpProQuiz_toplist')) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
if (!isset($this->_post['points']) || !isset($this->_post['totalPoints'])) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$quizId = $quiz->getId();
$userId = get_current_user_id();
$points = (int)$this->_post['points'];
$totalPoints = (int)$this->_post['totalPoints'];
$name = !empty($this->_post['name']) ? trim($this->_post['name']) : '';
$email = !empty($this->_post['email']) ? trim($this->_post['email']) : '';
$ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
$captchaAnswer = !empty($this->_post['captcha']) ? trim($this->_post['captcha']) : '';
$prefix = !empty($this->_post['prefix']) ? trim($this->_post['prefix']) : '';
$quizMapper = new WpProQuiz_Model_QuizMapper();
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
if ($quiz == null || $quiz->getId() == 0 || !$quiz->isToplistActivated()) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
if (!$this->preCheck($quiz->getToplistDataAddPermissions(), $userId)) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$numPoints = $quizMapper->sumQuestionPoints($quizId);
if ($totalPoints > $numPoints || $points > $numPoints) {
return array('text' => __('An error has occurred.', 'wp-pro-quiz'), 'clear' => true);
}
$clearTime = null;
if ($quiz->isToplistDataAddMultiple()) {
$clearTime = $quiz->getToplistDataAddBlock() * 60;
}
if ($userId > 0) {
if ($toplistMapper->countUser($quizId, $userId, $clearTime)) {
return array('text' => __('You can not enter again.', 'wp-pro-quiz'), 'clear' => true);
}
$user = wp_get_current_user();
$email = $user->user_email;
$name = $user->display_name;
} else {
if ($toplistMapper->countFree($quizId, $name, $email, $ip, $clearTime)) {
return array('text' => __('You can not enter again.', 'wp-pro-quiz'), 'clear' => true);
}
if (empty($name) || empty($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
return array('text' => __('No name or e-mail entered.', 'wp-pro-quiz'), 'clear' => false);
}
if (strlen($name) > 15) {
return array('text' => __('Your name can not exceed 15 characters.', 'wp-pro-quiz'), 'clear' => false);
}
if ($quiz->isToplistDataCaptcha()) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
if (!$captcha->check($prefix, $captchaAnswer)) {
return array('text' => __('You entered wrong captcha code.', 'wp-pro-quiz'), 'clear' => false);
}
}
}
}
$toplist = new WpProQuiz_Model_Toplist();
$toplist->setQuizId($quizId)
->setUserId($userId)
->setDate(time())
->setName($name)
->setEmail($email)
->setPoints($points)
->setResult(round($points / $totalPoints * 100, 2))
->setIp($ip);
$toplistMapper->save($toplist);
return true;
}
private function preCheck($type, $userId)
{
switch ($type) {
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ALL:
return true;
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ONLY_ANONYM:
return $userId == 0;
case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ONLY_USER:
return $userId > 0;
}
return false;
}
public static function ajaxAdminToplist($data)
{
if (!current_user_can('wpProQuiz_toplist_edit')) {
return json_encode(array());
}
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
$j = array('data' => array());
$limit = (int)$data['limit'];
$start = $limit * ($data['page'] - 1);
$isNav = isset($data['nav']);
$quizId = $data['quizId'];
if (isset($data['a'])) {
switch ($data['a']) {
case 'deleteAll':
$toplistMapper->delete($quizId);
break;
case 'delete':
if (!empty($data['toplistIds'])) {
$toplistMapper->delete($quizId, $data['toplistIds']);
}
break;
}
$start = 0;
$isNav = true;
}
$toplist = $toplistMapper->fetch($quizId, $limit, $data['sort'], $start);
foreach ($toplist as $tp) {
$j['data'][] = array(
'id' => $tp->getToplistId(),
'name' => $tp->getName(),
'email' => $tp->getEmail(),
'type' => $tp->getUserId() ? 'R' : 'UR',
'date' => WpProQuiz_Helper_Until::convertTime($tp->getDate(),
get_option('wpProQuiz_toplistDataFormat', 'Y/m/d g:i A')),
'points' => $tp->getPoints(),
'result' => $tp->getResult()
);
}
if ($isNav) {
$count = $toplistMapper->count($quizId);
$pages = ceil($count / $limit);
$j['nav'] = array(
'count' => $count,
'pages' => $pages ? $pages : 1
);
}
return json_encode($j);
}
public static function ajaxAddInToplist($data)
{
// workaround ...
$_POST = $_POST['data'];
$ctn = new WpProQuiz_Controller_Toplist();
$quizId = isset($data['quizId']) ? $data['quizId'] : 0;
$prefix = !empty($data['prefix']) ? trim($data['prefix']) : '';
$quizMapper = new WpProQuiz_Model_QuizMapper();
$quiz = $quizMapper->fetch($quizId);
$r = $ctn->handleAddInToplist($quiz);
if ($quiz->isToplistActivated() && $quiz->isToplistDataCaptcha() && get_current_user_id() == 0) {
$captcha = WpProQuiz_Helper_Captcha::getInstance();
if ($captcha->isSupported()) {
$captcha->remove($prefix);
$captcha->cleanup();
if ($r !== true) {
$r['captcha']['img'] = WPPROQUIZ_CAPTCHA_URL . '/' . $captcha->createImage();
$r['captcha']['code'] = $captcha->getPrefix();
}
}
}
if ($r === true) {
$r = array('text' => __('You signed up successfully.', 'wp-pro-quiz'), 'clear' => true);
}
return json_encode($r);
}
public static function ajaxShowFrontToplist($data)
{
// workaround ...
$_POST = $_POST['data'];
$quizIds = empty($data['quizIds']) ? array() : array_unique((array)$data['quizIds']);
$toplistMapper = new WpProQuiz_Model_ToplistMapper();
$quizMapper = new WpProQuiz_Model_QuizMapper();
$j = array();
foreach ($quizIds as $quizId) {
$quiz = $quizMapper->fetch($quizId);
if ($quiz == null || $quiz->getId() == 0) {
continue;
}
$toplist = $toplistMapper->fetch($quizId, $quiz->getToplistDataShowLimit(), $quiz->getToplistDataSort());
foreach ($toplist as $tp) {
$j[$quizId][] = array(
'name' => $tp->getName(),
'date' => WpProQuiz_Helper_Until::convertTime($tp->getDate(),
get_option('wpProQuiz_toplistDataFormat', 'Y/m/d g:i A')),
'points' => $tp->getPoints(),
'result' => $tp->getResult()
);
}
}
return json_encode($j);
}
}
and from model WpProQuiz_Model_Toplist.php:
<?php
class WpProQuiz_Model_Toplist extends WpProQuiz_Model_Model
{
protected $_toplistId;
protected $_quizId;
protected $_userId;
protected $_date;
protected $_name;
protected $_email;
protected $_points;
protected $_result;
protected $_ip;
public function setToplistId($_toplistId)
{
$this->_toplistId = (int)$_toplistId;
return $this;
}
public function getToplistId()
{
return $this->_toplistId;
}
public function setQuizId($_quizId)
{
$this->_quizId = (int)$_quizId;
return $this;
}
public function getQuizId()
{
return $this->_quizId;
}
public function setUserId($_userId)
{
$this->_userId = (int)$_userId;
return $this;
}
public function getUserId()
{
return $this->_userId;
}
public function setDate($_date)
{
$this->_date = (int)$_date;
return $this;
}
public function getDate()
{
return $this->_date;
}
public function setName($_name)
{
$this->_name = (string)$_name;
return $this;
}
public function getName()
{
return $this->_name;
}
public function setEmail($_email)
{
$this->_email = (string)$_email;
return $this;
}
public function getEmail()
{
return $this->_email;
}
public function setPoints($_points)
{
$this->_points = (int)$_points;
return $this;
}
public function getPoints()
{
return $this->_points;
}
public function setResult($_result)
{
$this->_result = (float)$_result;
return $this;
}
public function getResult()
{
return $this->_result;
}
public function setIp($_ip)
{
$this->_ip = (string)$_ip;
return $this;
}
public function getIp()
{
return $this->_ip;
}
}
I have this code:
public function getJccLineItem($id,$action)
{
$res = array();
$q = 'SELECT * FROM jcc_line_items jli,ipo_line_item ili ,line_items li
WHERE jli.line_item_id= ili.id and li.id = jli.line_item_id
and ili.dn_number_id in ( Select dn_number from ipo where project_id= '.$id.')';
$res = $this->db->query($q);
echo $this->db->last_query();
$jccLineItemArray = array();
echo $id;
print_r($res->result());
if($action == 'array')
{
foreach ( $res->result() as $key => $value) // The error comes in this line
{
$jccLineItemArray[ $value->id ] = $value->item_description;
}
$res = $jccLineItemArray;
}
else
{
$res = $res->result();
}
return $res;
}
The error is in the foreach loop. I have printed the result and it shows the result in object array but when it goes to foreach loop. It show this error
"Call to a member function result() on a non-object "
But when I set db['default']['db_debug']=true , it shows that the $id is missing from the query whereas when it was false it was showing result in object array and giving error at loop. Any Help would be appreciated.Thanks
Controller Code
public function createInvoice( $id = "" )
{
if (empty($id))
{
$id = $this->input->post('dataid');
}
echo $id;
$data['jcc_line_list'] = $this->product_model->getJccLineItem($id,'array');
$data['jcc_line_lists'] = $this->product_model->getJccLineItem($id,'');
$data['items'] = $this->product_model->getAllSubInvoice($id);
$data['single_project'] = $this->product_model->getSingleProject($id);
$data['site'] = $this->product_model->getAllSiteArray();
$data['job_types'] = $this->product_model->getAllJobTypeArray();
$data['title'] = 'Invoice';
$data['operation'] = 'Create';
$data['buttonText'] = 'Save';
$data['id'] = $id;
$this->load->helper(array('form', 'url'));
$this->load->helper('security');
$this->form_validation->set_rules('line_item_id', 'Line Item', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('job_type_id', 'Job Type', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('site_id', 'Site', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('milestone', 'Milestone', 'required|xss_clean|max_length[50]');
$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
if ($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('error_message', validation_errors());
$this->load->view('admin/viewinvoicesub', $data);
} else if ($this->form_validation->run() == TRUE) {
$formData = array(
'invoice_id' => $id,
'line_item_id' => $this->form_validation->set_value('line_item_id'),
'job_type_id' => $this->form_validation->set_value('job_type_id'),
'site_id' => $this->form_validation->set_value('site_id'),
'milestone' => $this->form_validation->set_value('milestone'),
);
$this->product_model->insertInvoiceSub($formData);
$this->session->set_flashdata('sucess_message', "Data successfully save !");
redirect('Products/createInvoice', "refresh");
} else {
$this->load->view('admin/viewinvoicesub', $data);
}
}
Try this and let me know if that helps
public function getJccLineItem($id = '' ,$action = '')
{
if($id != '')
{
$res = array();
$q = 'SELECT * FROM jcc_line_items jli,ipo_line_item ili ,line_items li
WHERE jli.line_item_id= ili.id and li.id = jli.line_item_id
and ili.dn_number_id in ( Select dn_number from ipo where project_id= '.$id.')';
$res = $this->db->query($q)->result();
$jccLineItemArray = array();
if($action == 'array')
{
foreach($res as $key => $value) // The error comes in this line
{
$jccLineItemArray[ $value->id ] = $value->item_description;
}
$res = $jccLineItemArray;
}
return $res;
}
else
{
echo "id is null"; die();
}
}
And your Controller code should be
public function createInvoice( $id = "" )
{
$this->load->helper(array('form', 'url'));
$this->load->helper('security');
if ($id = "")
{
$id = (isset($this->input->post('dataid')))?$this->input->post('dataid'):3;// i am sure your error is from here
}
$data['jcc_line_list'] = $this->product_model->getJccLineItem($id,'array');
$data['jcc_line_lists'] = $this->product_model->getJccLineItem($id,'');
$data['items'] = $this->product_model->getAllSubInvoice($id);
$data['single_project'] = $this->product_model->getSingleProject($id);
$data['site'] = $this->product_model->getAllSiteArray();
$data['job_types'] = $this->product_model->getAllJobTypeArray();
$data['title'] = 'Invoice';
$data['operation'] = 'Create';
$data['buttonText'] = 'Save';
$data['id'] = $id;
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$this->form_validation->set_rules('line_item_id', 'Line Item', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('job_type_id', 'Job Type', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('site_id', 'Site', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('milestone', 'Milestone', 'required|xss_clean|max_length[50]');
$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
if ($this->form_validation->run() === FALSE)
{
$this->session->set_flashdata('error_message', validation_errors());
$this->load->view('admin/viewinvoicesub', $data);
}
else
{
$formData = array(
'invoice_id' => $id,
'line_item_id' => $this->form_validation->set_value('line_item_id'),
'job_type_id' => $this->form_validation->set_value('job_type_id'),
'site_id' => $this->form_validation->set_value('site_id'),
'milestone' => $this->form_validation->set_value('milestone'),
);
$this->product_model->insertInvoiceSub($formData);
$this->session->set_flashdata('sucess_message', "Data successfully save !");
redirect('Products/createInvoice/'.$id, "refresh");
}
}
else
{
$this->load->view('admin/viewinvoicesub', $data);
}
}
I'm using codeigniter and this is located in my model. I have this error Unknown column 'postTable' in 'field list' . I hope you can help me and thank you in advance.
public function getManufacturer()
{
$condition = array('manufacturer_id' => $this->manufacturer_id);
$query = $this->db->get_where('manufacturer', $condition);
return $query->row_array();
}
public function updateManufacturer()
{
$this->db->where('manufacturer_id',$this->manufacturer_id);
$query = $this->db->update('manufacturer', $this);
return $query;
}
And this is my controller
public function updateForm()
{
$data = array();
$this->load->model('asset_model');
$p = new asset_model();
$p->manufacturer_id = $this->input->post('manufacturer_id');
$data = $p->getManufacturer();
$this->load->view('updateForm',$data);
}
public function update()
{
$this->load->model('asset_model');
$p = new asset_model();
$p->manufacturer_id = $this->input->post('manufacturer_id');
$p->manufacturer_name = $this->input->post('manufacturer_name');
$status = $p->updateManufacturer();
if ($status == true) {
redirect('asset_management/manufacturers');
}
}
Try this
In your controller
public function updateForm()
{
$data = array();
$this->load->model('asset_model');
$manufacturer_id = $this->input->post('manufacturer_id');
$data = $this->asset_model->getManufacturer($manufacturer_id);
$this->load->view('updateForm',$data);
}
public function update()
{
$this->load->model('asset_model');
$manufacturer_id = $this->input->post('manufacturer_id');
$manufacturer_name = $this->input->post('manufacturer_name');
$status = $this->asset_model->getManufacturer($manufacturer_id);
if ($status == true) {
redirect('asset_management/manufacturers');
}
}
In Model
public function getManufacturer($manufacturer_id)
{
$condition = array('manufacturer_id' =>$manufacturer_id);
$query = $this->db->get_where('manufacturer', $condition);
return $query->row_array();
}
public function updateManufacturer($manufacturer_id)
{
$condition = array('manufacturer_id' =>$manufacturer_id);
$query = $this->db->update('manufacturer', $condition);
return $query;
}
Codeigniter when i submit more than one option of form_multiselect(), Only just the last one that saved on database.
in my view :
<label>Trimestres :</label>
<div class="controls" >
<?php $options = array(
'trim1' => ' Premier trimestre (Janv,Fév,Mars)',
'trim2' => ' Deuxiéme trimestre (Avril,Mai,Juin)',
'trim3' => ' Troisiéme trimestre (Juill,Aout,Sept)',
'trim4' => ' Quatriéme trimestre (Oct,Nov,Déc)',
);
echo form_multiselect('trimestres', $options , $this->input->post('trimestres') ? $this->input->post('trimestres') : $participant_sport->trimestres, 'id="trim"'); ?>
</div>
</div>
in my controller :
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
}
else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// Process the form
$this->participantsport_m->array_from_post(array('matricule', 'nom', 'prenom', 'beneficiaire', 'sexe', 'telephone', 'date_naissance', 'date_inscription_sport', 'trimestres' ,'sport_montant_paye', 'sport_debut_periode', 'sport_fin_periode'));
$this->participantsport_m->save($data, $id);
redirect('admin/agent/profile/3608');
}
// Load the view
$this->data['subview'] = 'admin/agent/inscriresport';
$this->load->view('admin/_layout_main', $this->data);
}
The function array_from_post() is defined on application\core\MY_Model.php :
public function array_from_post($fields){
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
in my model :
public function get_new()
{
$participant_sport = new stdClass();
$participant_sport->matricule = '';
$participant_sport->nom = '';
$participant_sport->prenom = '';
$participant_sport->beneficiaire = '';
$participant_sport->sexe = '';
$participant_sport->telephone = '';
$participant_sport->date_naissance = '';
$participant_sport->date_inscription_sport = '';
$participant_sport->trimestres = '';
$participant_sport->sport_montant_paye = '';
$participant_sport->sport_debut_periode = '';
$participant_sport->sport_fin_periode = '';
return $participant_sport;
}
Any help Please? i think that must be an array but i don't know how to do it?
i thing that i must do something like that :
foreach($_POST["strategylist[]"] as $s) {
# do the insert here, but use $s instead of $_POST["strategylist[]"]
$result=mysql_query("INSERT INTO sslink (study_id, strategyname) " .
"VALUES ('$id','" . join(",",$s) . "')")
or die("Insert Error: ".mysql_error());
}
to insert more than one option selected in one row but i don't know how to do it in codeigniter
the get() function :
public function get($id = NULL, $single = FALSE){
if ($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
}
elseif($single == TRUE) {
$method = 'row';
}
else {
$method = 'result';
}
if (!count($this->db->ar_orderby)) {
$this->db->order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
If select name (in HTML tag) is trimestres it will always remember last selection. Use trimestres[] as a name to get array with all selected values`
<select name="trimestres[]" multiple …
By the way:
I don't know how array_from_post() works but it has to change trimestres[] values to one string to save all of them in one column. It is hard to search/add/delete one value if all values are in one string. It is "SQL Antipattern". You could do another table in database for trimestres - one value in one row.
Edit:
It will change all arrays into string with elements connected by ,. Not tested.
public function array_from_post($fields){
$data = array();
foreach ($fields as $field) {
// print_r($this->input->post($field));
if( is_array( $this->input->post($field) ) ) {
$data[$field] = join(",", $this->input->post($field));
} else {
$data[$field] = $this->input->post($field);
}
// print_r($data[$field]);
}
return $data;
}
Edit:
Not tested.
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
// explode to array
// print_r($this->data['participant_sport']->trimestres); // test before explode
// $this->data['participant_sport']['trimestres'] = explode(",", $this->data['participant_sport']['trimestres']);
$this->data['participant_sport']->trimestres = explode(",", $this->data['participant_sport']->trimestres);
// print_r($this->data['participant_sport']->trimestres); // test after explode
} else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// rest of code
}
There is a easy way to solve this problem that I found today.
you have to serialize the $_POST['trimestres'] array just after array_form_post .
the this array will save to database as a serialize string.
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
}
else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// Process the form
$this->participantsport_m->array_from_post(array('matricule', 'nom', 'prenom', 'beneficiaire', 'sexe', 'telephone', 'date_naissance', 'date_inscription_sport', 'trimestres' ,'sport_montant_paye', 'sport_debut_periode', 'sport_fin_periode'));
$data['trimestres'] = serialize($_POST['trimestres']);
$this->participantsport_m->save($data, $id);
redirect('admin/agent/profile/3608');
}
// Load the view
$this->data['subview'] = 'admin/agent/inscriresport';
$this->load->view('admin/_layout_main', $this->data);
}
When you just need this data back form database just use php unserialize() function .
Hope it will help to do this easily ....
-thanks
I'm trying to add a final field to my project that contains a URL of the files that have been uploaded, if anyone could point me in the write direction for extending my model ?
I have included my codeIgniter Model & Controller code.
controller:
class Canvas extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index() {
$vars = array();
//$this->load->library('ChromePhp');
//$this->ChromePhp->log('test');
//$this->ChromePhp->log($_SERVER);
// using labels
// foreach ($_SERVER as $key => $value) {
// $this->ChromePhp->log($key, $value);
// }
// warnings and errors
//$this->ChromePhp->warn('this is a warning');
//$this->ChromePhp->error('this is an error');
$this->load->library('FacebookConnect');
$facebook=$this->facebookconnect->connect();
$vars['facebook'] = $facebook;
$user = $vars['user'] = $facebook->getUser();
$this->load->model('Users_Model');
// user already set up. Show thank you page
if($user != 0 && sizeof($_POST)>0) {
$this->do_upload();
$this->iterate_profile ($vars['user'],false,$_POST);
$this->load->view('canvas',$vars);
} else {
// user not set, show welcome message
$this->load->view('canvas',$vars);
}
}
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '20048';
$config['max_width'] = '10624';
$config['max_height'] = '10268';
$config['file_name'] = date("Y_m_d H:i:s");
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
function thank_you() {
$this->load->view('thank_you',$vars);
}
function remove() {
$vars = array();
$this->load->library('FacebookConnect');
$facebook=$this->facebookconnect->connect();
$vars['facebook'] = $facebook;
$vars['user'] = $facebook->getUser();
$this->load->model('Users_Model');
if($vars['user'] == 0) {
// user not set, redirect
redirect('/', 'refresh');
} else {
// user already set up. Remove
$this->load->model('Users_Model');
$this->Users_Model->remove($vars['user']);
}
$this->load->view('removed',$vars);
}
protected function iterate_profile ($user,$breadcrumb,$item) {
foreach($item as $key => $value) {
if(is_array($value)) {
$this->iterate_profile($user,$key,$value);
}
else {
if($breadcrumb) {
//echo '[' . $breadcrumb . '_' . $key . ']= ' . $value . ' <br />';
$key = $breadcrumb . '_' . $key;
}
if( ! $this->Users_Model->exists($user,$key)) {
// does not exist in the database, insert it
$this->Users_Model->add($user,$key,$value);
} else {
$this->Users_Model->update($user,$key,$value);
}
}
}
}
}
Model:
class Users_Model extends CI_Model {
protected $_name = 'users';
function add($id,$key,$value) {
$data = array(
'id' => $id,
'name' => $key,
'value' => $value
);
return $this->db->insert($this->_name, $data);
}
function update($id,$key,$value) {
$data = array(
'value' => $value
);
$this->db->where(array(
'id' => $id,
'name' => $key
));
return $this->db->update($this->_name, $data);
}
function exists($id,$key=null) {
if($key == null) {
$this->db->where(array(
'id' => $id
));
} else {
$this->db->where(array(
'id' => $id,
'name' => $key
));
}
$query = $this->db->get($this->_name);
if($query->num_rows() > 0) {
return true;
}
return false;
}
function remove($id) {
$data = array(
'id' => $id,
);
return $this->db->delete($this->_name, $data);
}
function all() {
$query = $this->db->get($this->_name);
$results = array();
if($query->num_rows() > 0) {
foreach($query->result() as $row) {
$results[]=$row;
}
}
return $results;
}
}
I don't think the question is very clear. But to me it seems you need to store the image path in the db. Otherwise you will need to perform a read directory on the upload path and then do something with the images.