On my controller I have a error on this line 'edit' => site_url('admin/users_group_controller_update') .'/'. $this->getId($controller)
When I refresh my page it throws the error Array to string conversion
A PHP Error was encountered Severity: Notice Message: Array to string
conversion Filename: user/users_group_update.php Line Number: 47
Not sure what to do on that because I need to add variable $controller in to $this->getId($controller);
What changes is best suited to make this work.
<?php
class Users_group_update extends Admin_Controller {
public function __construct() {
parent::__construct();
$this->load->model('admin/user/model_user_group');
}
public function index() {
$data['title'] = "Users Group Update";
$controller_files = $this->getInstalled($this->uri->segment(3));
$data['controller_files'] = array();
$files = glob(FCPATH . 'application/modules/admin/controllers/*/*.php');
if ($files) {
foreach ($files as $file) {
$controller = basename(strtolower($file), '.php');
$do_not_list = array(
'customer_total',
'dashboard',
'footer',
'header',
'login',
'logout',
'menu',
'online',
'permission',
'register',
'user_total'
);
if (!in_array($controller, $do_not_list)) {
$data['controller_files'][] = array(
'name' => $controller,
'installed' => in_array($controller, $controller_files),
'edit' => site_url('admin/users_group_controller_update') .'/'. $this->getId($controller)
);
}
}
}
$this->load->view('template/user/users_group_form_update', $data);
}
public function getInstalled($name) {
$controller_data = array();
$this->db->select();
$this->db->from($this->db->dbprefix . 'user_group');
$this->db->where('name', $name);
$query = $this->db->get();
foreach ($query->result_array() as $result) {
$controller_data[] = $result['controller'];
}
return $controller_data;
}
public function getId($controller) {
$this->db->select();
$this->db->from($this->db->dbprefix . 'user_group');
$this->db->where('name', $this->uri->segment(3));
$this->db->where('controller', $controller);
$query = $this->db->get();
return $query->row('user_group_id');
}
}
View
<?php echo Modules::run('admin/common/header/index');?>
<div id="wrapper">
<?php echo Modules::run('admin/common/menu/index');?>
<div id="page-wrapper" >
<div id="page-inner">
<?php
$data = array(
'class' =>
'form-horizontal',
'id' =>
'form-users-group'
);
echo form_open_multipart('admin/users_group_update' .'/'. $this->uri->segment(3), $data);?>
<div class="panel panel-default">
<div class="panel-heading clearfix">
<div class="pull-left" style="padding-top: 7.5px"><h1 class="panel-title"><?php echo $title;?></h1></div>
<div class="pull-right">
Cancel
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
<div class="panel-body">
<?php echo validation_errors('<div class="alert alert-warning text-center">', '</div>'); ?>
<div class="form-group">
<?php
$data = array(
'class' => 'col-sm-2'
);
echo form_label('User Group Name', 'name', $data)
;?>
<div class="col-sm-10">
<?php
$data = array(
'id' => 'name',
'name' => 'name',
'class' => 'form-control',
'value' => set_value('name')
);
echo form_input($data)
;?>
</div>
</div>
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>Controller Name</td>
<td>Access</td>
<td>Modify</td>
</tr>
</thead>
<tbody>
<?php if ($controller_files) { ?>
<?php foreach ($controller_files as $controllers) { ?>
<tr>
<td>
<div class="clearfix">
<div class="pull-left">
<?php echo $controllers['name']; ?>
</div>
<div class="pull-right">
<?php if ($controllers['installed']) { ?>
<span class="label label-success">Installed</span>
<span class="label label-danger"><a style="color: #FFF; text-decoration: none;" href="<?php echo $controllers['edit'];?>">Edit Individual Controller</a></span>
<?php } else { ?>
<span class="label label-primary">Not Installed</span>
<?php } ?>
</div>
</div>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
</div>
<div class="panel-footer">
</div>
</div><!-- Panel End -->
<?php echo form_close();?>
</div><!-- # Page Inner End -->
</div><!-- # Page End -->
</div><!-- # Wrapper End -->
<?php echo Modules::run('admin/common/footer/index');?>
Change this line
'edit' => site_url('admin/users_group_controller_update') .'/'. $this->getId($controller)
to
'edit' => site_url('admin/users_group_controller_update' .'/'. $this->getId($controller))
With in my files variable I had to use the db function to get it to work. No errors show now all fixed.
<?php
class Users_group_update extends Admin_Controller {
public function __construct() {
parent::__construct();
$this->load->model('admin/user/model_user_group');
}
public function index() {
$data['title'] = "Users Group Update";
$controller_files = $this->getInstalled($this->uri->segment(3));
$data['controller_files'] = array();
$files = glob(FCPATH . 'application/modules/admin/controllers/*/*.php');
if ($files) {
foreach ($files as $file) {
$controller = basename(strtolower($file), '.php');
$do_not_list = array(
'customer_total',
'dashboard',
'footer',
'header',
'login',
'logout',
'menu',
'online',
'permission',
'register',
'user_total'
);
if (!in_array($controller, $do_not_list)) {
$this->db->where('name', $this->uri->segment(3));
$this->db->where('controller', $controller);
$query = $this->db->get($this->db->dbprefix . 'user_group');
if ($query->num_rows()) {
$row = $query->row();
$data['controller_files'][] = array(
'name' => $controller,
'installed' => in_array($controller, $controller_files),
'edit' => site_url('admin/users_group_controller_update' .'/'. $row->user_group_id)
);
}
}
}
}
$this->load->view('template/user/users_group_form_update', $data);
}
public function getInstalled($name) {
$controller_data = array();
$this->db->select();
$this->db->from($this->db->dbprefix . 'user_group');
$this->db->where('name', $name);
$query = $this->db->get();
foreach ($query->result_array() as $result) {
$controller_data[] = $result['controller'];
}
return $controller_data;
}
}
Related
How to get value form multiples checkbox and post array in codeigniter? I have problem when I get value post array and echo the value. I see only the value of the last checked checkbox. How to show post value when submit?
You find three files: view, Controller and Model. 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($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>
</tbody>
</table>
</div>
</div>
</div>
PAGE_MODEL.PHP:
<?php class Page_model extends CI_Model
{
public function input_values()
{
$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),
'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),
'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' => $this->input->post('subcat_recip_id')
for ($i=0; $i<count($menu_links); $i++)
{
echo $subcat_recip_id[$i];
}
);
return $data;
}
//add page
public function add()
{
$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();
}
}
return $this->db->insert('pages', $data);
}
//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;
}
PAGE_CONTROLLER.PHP
* Add Page Post*/
public function add_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 {
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->add()) {
$this->session->set_flashdata('success', trans("page") . " " . trans("msg_suc_added"));
redirect($this->agent->referrer());
} else {
$this->session->set_flashdata('form_data', $this->page_model->input_values());
$this->session->set_flashdata('error', trans("msg_error"));
redirect($this->agent->referrer());
}
}
}
I have tried this code
in your Page_model put this code.
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),
'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),
'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
);
}
public function checkBox(){
$count = count($_POST['subcat_recip_id']);
for($n=0; $n<$count; $n++){
$checkbox[$n] = $_POST['subcat_recip_id'][$n];
}
return $checkbox;
}
hopefully it helps
This is what $menu_links is:
public function get_menu_links_by_lang()
{
$lang_id = $this->input->post('lang_id', true);
if (!empty($lang_id)):
$menu_links = $this->navigation_model->get_menu_links_by_lang($lang_id);
foreach ($menu_links as $item):
if ($item["type"] != "category" && $item["location"] == "header" && $item['parent_id'] == "0"):
echo ' <option value="' . $item["id"] . '">' . $item["title"] . '</option>';
endif;
endforeach;
endif;
}
I edited a code to insert new form page and I need this page to enter some values into DB. All works Ok and they inserted to DB, only the checkbox doesn't work or better it take only the value of the last checked checkbox and not all the checkbox checked! I have tried it in many ways but I can't do it alone. Sorry.
I tried to implement standard PHP logic for add, edit articles to blog, so i have add method:
public function add()
{
$this->load->model('admin/Blog_Model');
if (!empty($this->input->post())) {
$user = $this->Blog_Model->addPost($this->input->post());
}
$this->getForm();
}
edit method:
public function edit($id = '')
{
$this->load->model('admin/Blog_Model');
if (!empty($this->input->post())) {
var_dump($id); exit;
$user = $this->Blog_Model->editPost($this->input->post(), $id);
}
$this->getForm($id);
}
and getForm method:
public function getForm($id = '')
{
if (!empty($id)) {
$post = $this->Blog_Model->getPost($id);
$data['action'] = 'admin/blog/edit';
} else {
$data['action'] = 'admin/blog/add';
}
$data['formTitle'] = array(
'name' => 'title',
'id' => 'content-title',
'value' => isset($post['title']) ? $post['title'] : '',
'placeholder' => 'Заглавие',
'class' => 'form-control'
);
$data['formContent'] = array(
'name' => 'content',
'id' => 'content-blog',
'value' => isset($post['content']) ? $post['content'] : '',
'placeholder' => 'Съдържание',
);
$data['formButton'] = array(
'type' => 'submit',
'content'=> 'Изпрати',
'class'=> 'btn btn-primary btn-block btn-flat'
);
$data['head'] = $this->load->view('admin/head', NULL, TRUE);
$data['left_column'] = $this->load->view('admin/left_column', NULL, TRUE);
$this->load->view('admin/header', $data);
$this->load->view('admin/blog_form', $data);
$this->load->view('admin/footer');
}
and blog_form view with form:
<div class="box-body pad">
<?php echo form_open($action); ?>
<div class="box-body">
<div class="form-group">
<label for="content-title">Заглавие:</label>
<?php echo form_input($formTitle); ?>
</div>
<div class="form-group">
<label for="content_blog">Съдържание:</label>
<?php echo form_textarea($formContent); ?>
</div>
<div class="col-xs-12 col-md-3 pull-right">
<?php echo form_button($formButton); ?>
</div>
</div>
<?php echo form_close(); ?>
</div>
So .. everything works perfect, but i have problem with this part:
if (!empty($id)) {
$post = $this->Blog_Model->getPost($id);
$data['action'] = 'admin/blog/edit';
} else {
$data['action'] = 'admin/blog/add';
}
if it's edit i want to send id like GET parameter. I think the problem is there than i does not use standard GET parameters instead of site_url function, when i show all articles here:
<?php foreach ($posts as $post) { ?>
<tr>
<td><?php echo $post['id']; ?></td>
<td><?php echo $post['title']; ?></td>
<td><?php echo $post['content']; ?></td>
<td><div class="btn-group">
Редактирай
Изтрий
</div></td>
</tr>
<?php } ?>
Try to change
if (!empty($id)) {
$post = $this->Blog_Model->getPost($id);
$data['action'] = 'admin/blog/edit';
} else {
$data['action'] = 'admin/blog/add';
}
to
if (!empty($id)) {
$post = $this->Blog_Model->getPost($id);
$data['action'] = 'admin/blog/edit/'.$id; // pass $id to edit controller
} else {
$data['action'] = 'admin/blog/add';
}
I am trying to upload files from a form and then save it in a directory uvis_front_user_files which is located under web/uploads but when i save the form everything goes well but the files are not there in the destination directory.
Even the file name is saved in database but in the uvis_front_user_files directory there is nothing.
Form:
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="heading heading-tertiary heading-border text-center">
<h4 class="heading-tertiary"><?php echo $quiz['title'] ?></h4>
<p><?php echo $quiz['description'] ?></p>
</div>
<?php if ($sf_user->hasFlash('success')): ?>
<div class="alert alert-success">
<?php echo $sf_user->getFlash('success'); ?>
</div>
<?php endif; ?>
<div class="col-md-6 col-md-offset-3">
<form method="POST" action="" enctype="multipart/form-data">
<?php echo $form->renderGlobalErrors(); ?>
<table class="sample-order-frm" width="100%">
<?php echo $form['name']->renderRow() ?>
<?php echo $form['email']->renderRow() ?>
</tr>
</table>
<?php $current = current($quiz['questions']) ?>
<?php if ($current["text"] !== NULL): ?>
<h4 class="heading-tertiary">Please leave blank the questions that do not apply:</h4>
<ol class="survey-ques-list">
<?php foreach ($quiz['questions'] as $questionId => $question): ?>
<li>
<label><?php echo $question['text']; ?></label>
<?php echo $form['question_'.$questionId]->render(); ?>
<?php echo $form['path']->render(); ?>
<?php echo $form['question_'.$questionId]->renderError(); ?>
</li>
<?php endforeach; ?>
</ol>
<br />
<?php endif; ?>
<?php echo $form->renderHiddenFields(false); ?>
<div class="text-center">
<input type="submit" id="submit" name="submit" value="Submit" class="btn btn-tertiary btn-lg"/>
</div>
</form>
</div>
</div>
</div>
</div>
Action File:
<?php
/**
* uvisQuiz actions.
*
* #package we.com
* #subpackage uvisQuiz
* #version SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
*/
class uvisQuizActions extends sfActions {
/**
* Executes index action
*
* #param sfRequest $request A request object
*/
public function executeIndex(sfWebRequest $request) {
$this->forward404Unless($slug = $request->getParameter('slug'));
$this->forward404Unless($this->quiz = UvisQuizFrontPeer::getQuizBySlug($slug));
$this->form = new UvisQuizCustomForm(null, array('questions' => $this->quiz['questions']));
if($request->isMethod('POST')){
$params = $request->getParameter($this->form->getName());
$this->form->bind($params, $request->getFiles($this->form->getName()));
//$this->form->bind($params);
if($this->form->isValid()){
$uvisQuizUserObj = UvisQuizFrontPeer::saveQuiz($this->quiz, $params);
$this->getUser()->setFlash('completed_video_survey', true);
$this->redirect('#uvis_quiz_complete?slug='.$request->getParameter('slug'));
}
}
}
public function executeComplete(sfWebRequest $request) {
$this->forward404Unless($slug = $request->getParameter('slug'));
$this->forward404Unless($this->singleQuiz = UvisQuizFrontPeer::getQuizBySlug($slug));
$this->forward404Unless($this->getUser()->hasFlash('completed_video_survey'));
}
}
UvisQuizFrontPeer:
<?php
class UvisQuizFrontPeer extends BaseUvisQuizPeer {
public static function getQuizBySlug($slug) {
$criteria = new Criteria();
$criteria->addSelectColumn('uvis_quiz.id as id');
$criteria->addSelectColumn('uvis_quiz.title as title');
$criteria->addSelectColumn('uvis_quiz.description as description');
$criteria->addSelectColumn('uvis_quiz.path as path');
$criteria->addSelectColumn('uvis_quiz_question.id as question_id');
$criteria->addSelectColumn('uvis_quiz_question.question as question_text');
$criteria->addSelectColumn('uvis_quiz_question.answer_type as answer_type');
$criteria->addSelectColumn('uvis_quiz_question_answer.id as answer_id');
$criteria->addSelectColumn('uvis_quiz_question_answer.answer as answer_text');
$criteria->addJoin(self::ID, UvisQuizQuestionPeer::QUIZ_ID, Criteria::LEFT_JOIN);
$criteria->addJoin(UvisQuizQuestionPeer::ID, UvisQuizQuestionAnswerPeer::QUIZ_QUESTION_ID, Criteria::LEFT_JOIN);
$criteria->add(self::SLUG, $slug);
$criteria->add(self::DELETED_AT, null, Criteria::ISNULL);
$criteria->add(UvisQuizQuestionPeer::DELETED_AT, null, Criteria::ISNULL);
$criteria->add(UvisQuizQuestionAnswerPeer::DELETED_AT, null, Criteria::ISNULL);
$records = self::doSelectStmt($criteria)->fetchAll(PDO::FETCH_ASSOC);
$quizData = array();
foreach ($records as $record) {
if (!isset($quizData['id'])) {
$quizData['id'] = $record['id'];
$quizData['title'] = $record['title'];
$quizData['description'] = $record['description'];
$quizData['path'] = $record['path'];
$quizData['questions'] = array();
}
if (!isset($quizData['questions'][$record['question_id']])) {
$quizData['questions'][$record['question_id']]['text'] = $record['question_text'];
$quizData['questions'][$record['question_id']]['type'] = $record['answer_type'];
$quizData['questions'][$record['question_id']]['answer_choices'] = array();
$quizData['questions'][$record['question_id']]['answers'] = array();
}
if (!isset($quizData['questions'][$record['question_id']]['answers'][$record['answer_id']])) {
$quizData['questions'][$record['question_id']]['answer_choices'][$record['answer_id']] = $record['answer_text'];
$quizData['questions'][$record['question_id']]['answers'][$record['answer_id']]['text'] = $record['answer_text'];
}
}
return count($quizData) > 0 ? $quizData : false;
}
public static function saveQuiz($quizData, $params) {
$uvisQuizUserObj = new UvisQuizUser();
$uvisQuizUserObj->setQuizId($quizData['id']);
$uvisQuizUserObj->setName($params['name']);
$uvisQuizUserObj->setEmail($params['email']);
$uvisQuizUserObj->save();
foreach ($quizData['questions'] as $questionId => $question) {
if(isset($params['question_'.$questionId]) && $params['question_'.$questionId] != ''){
$uvisQuizUserAnswerObj = new UvisQuizUserAnswer();
$uvisQuizUserAnswerObj->setQuizUserId($uvisQuizUserObj->getId());
$uvisQuizUserAnswerObj->setQuiestionId($questionId);
if($question['type'] == 'free_text'){
$uvisQuizUserAnswerObj->setFreeTextAnswer($params['question_'.$questionId]);
$uvisQuizUserAnswerObj->setPath($params['path']);
}
else{
$uvisQuizUserAnswerObj->setAnswerId($params['question_'.$questionId]);
}
$uvisQuizUserAnswerObj->save();
}
}
return $uvisQuizUserObj;
}
}
QuizCustomForm:
<?php
class UvisQuizCustomForm extends sfForm {
public function configure() {
$mimeTypes = array('application/pdf', 'application/x-pdf', 'application/rtf',
'application/vnd.oasis.opendocument.text', 'application/msword',
'application/vnd.oasis.opendocument.spreadsheet',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/x-msword', 'text/plain');
$this->widgetSchema['name'] = new sfWidgetFormInput(array(), array('class' => 'form-control'));
$this->widgetSchema['email'] = new sfWidgetFormInput(array(), array('class' => 'form-control'));
$this->widgetSchema['phone'] = new sfWidgetFormInput();
$this->validatorSchema['name'] = new sfValidatorString(array('max_length' => 64, 'required' => true, 'trim' => 'both'), array('required' => 'Name is required', 'max_length' => 'Maximum %max_length% characters allowed'));
$this->validatorSchema['email'] = new sfValidatorEmail(array('max_length' => 255, 'required' => true, 'trim' => 'both'), array('required' => 'Email is required', 'max_length' => 'Maximum %max_length% characters allowed', 'invalid' => 'Invalid email'));
$this->validatorSchema['phone'] = new sfValidatorRegex(array('pattern' => '/^[0-9\-]+$/', 'required' => false), array('invalid' => 'Invalid phone number'));
foreach ($this->options['questions'] as $questionId => $question) {
if($question['type'] == 'multiple'){
$this->widgetSchema['question_' . $questionId] = new sfWidgetFormChoice(array('choices' => $question['answer_choices'], 'expanded' => true));
$this->validatorSchema['question_' . $questionId] = new sfValidatorChoice(array('required' => false, 'choices' => array_keys($question['answer_choices'])), array('invalid' => 'Invalid option selected'));
} else {
$this->widgetSchema['path'] = new sfWidgetFormInputFile(array(
'label' => 'Upload File',
));
$this->setValidator('path', new sfValidatorFile(array(
'required' => false,
'path' => sfConfig::get('sf_upload_dir').'/uvis_front_user_files',
'mime_types' => $mimeTypes,
)));
$this->widgetSchema['question_' . $questionId] = new sfWidgetFormTextarea(array(), array('cols' => 50, 'rows' => 4));
$this->validatorSchema['question_' . $questionId] = new sfValidatorString(array('required' => false));
}
}
$this->widgetSchema['quiz_user_id'] = new sfWidgetFormInputHidden();
$this->validatorSchema['quiz_user_id'] = new sfValidatorPropelChoice(array('model' => 'UvisQuizUser', 'column' => 'id', 'required' => false));
$decorator = new sfWidgetFormSchemaFormatterMain($this->widgetSchema, $this->validatorSchema);
$this->widgetSchema->addFormFormatter('custom', $decorator);
$this->widgetSchema->setFormFormatterName('custom');
$this->widgetSchema->setNameFormat('UvisQuizFrontForm[%s]');
}
}
Just give write permission to the folder and check
Im quiet new to codeigniter and i am having some trouble setting up my shopping cart. plzz help!!
This is my model:
class shop_model extends CI_Model
{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get_all() {
$results = $this->db->get('product')->result();
return $results;
}
function get($id) {
$results = $this->db->get_where('product', array('id' => $id))->row_array();
$result = $results[0];
//result()
return $result;
}
}
my controller:
class shop extends CI_Controller {
public function __construct()
{
parent::__construct();
//$this->load->library(array('form_validation', 'email','pagination'));
$this->load->database();
$this->load->model('shop_model');
}
public function index()
{
$data['products'] = $this->shop_model->get_all();
//print_r($data['products']);
$this->load->view('template/header');
$this->load->view('watch_stop/vprod_list', $data);
$this->load->view('template/footer');
}
public function prod_cart(){
$data['title'] = 'Shopping Cart | Watch Stop';
$this->load->view('template/header');
$this->load->view('watch_stop/vcart', $data);
$this->load->view('template/footer');
}
function add(){
$prod_list = $this->shop_model->get($this->input->post('id'));
$id = $this->input->post('id');
$insert = array(
'id' => $this->input->post('id'),
'qty' => 1,
'price' => $prod_list->price,
'name' => $prod_list->title
);
$this->cart->insert($insert);
print_r($this->cart->contents());
//redirect('shop/prod_cart');
}
}
my cart (view) page:
<div class="row">
<div class="col-md-9">
<?php if ($cart = $this->cart->contents()): ?>
<div id="cart">
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Item Name</th>
<th>Option</th>
<th>Price</th>
<th></th>
</tr>
</thead>
<tbody>
<?php foreach ($cart as $item): ?>
<tr>
<td><?php echo heading($item['brand'].' - '.$item['gender'], 5).br().$item['title'];?></td>
<td><?php ?></td>
<td><?php echo $item['subtotal']; ?></td>
<td class="remove"><?php anchor('shop/remove'.$item['rowid'], '<i class="fa fa-times fa-2x"></i>'); ?> </td>
<tr>
<?php endforeach; ?>
<tr class="total">
<td colspan="2"><strong>Total:</strong></td>
<td>LKR <?php echo $this->cart->total(); ?></td>
</tr>
</tbody>
</table>
</div> <!--table-responsive end-->
</div> <!--cart end-->
<?php endif; ?>
</div> <!--col-md-9 end-->
</div> <!--.row end-->
my products list (view) page (this page is populated via another controller and model and works perfectly):
<div class="row na_top ws-brand-head">
<!--column 1 start-->
<div class="col-md-12">
<?php
echo heading($sub_head, 2);
echo '<hr>';
?>
</div> <!--column 1 end-->
</div> <!--row end-->
<div class="row">
<?php echo $this->session->flashdata('msg'); ?>
<?php foreach($products as $prod_list): ?>
<!--Column 2 start-->
<div class="col-md-3 ws-brand">
<div id="products" class="naprod naprod-mar">
<?php
$na_1 = array(
'src' => base_url().$prod_list['image'],
'height' => '150',
'alt' => $prod_list['title']
);
echo form_open('shop/add');
echo heading($prod_list['stock'], 5);
echo '<div class="na-img">'.img($na_1).'</div>';
echo '<div class="nacont">';
echo anchor(site_url('product/'.$prod_funct.'/'.$prod_list['id']),'<p class="na-btn">VIEW</p>');
?>
<!--<input type="text" id="id" name="id" value="<?php //echo $prod_list['id'] ; ?>" style=" display:none;"/>-->
<input type="hidden" name="id" value="<?php echo $prod_list['id'] ; ?>" />
<button type="submit" name="action" class="na-btn"><i class='fa fa-shopping-cart fa-lg'></i></button>
<?php
echo '</div>';
echo br();
echo heading('LKR '.$prod_list['price'], 5);
echo '<div id="'.$prod_list['brand'].'_'.$prod_list['gender'].'_'.$prod_list['id'].'">'.$prod_list['title'].'</div>';
echo form_close();
?>
</div> <!--naprod naprod-mar end-->
</div> <!--column 2 end-->
<?php endforeach; ?>
</div> <!--row end-->
When i try to load the shop/add method im getting the following errors:
1)Trying to get property of non-object in my controller shop: line 40 and 41. That is the line where i have created the $insert array 'price' and 'name'.
You have to verify if there is catched $prod_list after you try to catch it with your shop model.. (I am not quite sure what your method get is returning but false check should be enough)
function add(){
$prod_list = $this->shop_model->get($this->input->post('id'));
if( ! $prod_list ) {
echo "Product doesn't exists";
exit;
}
$id = $this->input->post('id');
$insert = array(
'id' => $this->input->post('id'),
'qty' => 1,
'price' => $prod_list->price,
'name' => $prod_list->title
);
$this->cart->insert($insert);
print_r($this->cart->contents());
//redirect('shop/prod_cart');
}
This is my code in actionCheckout():
public function actionCheckout() {
$proInfo = Yii::app()->session['cart'];
if (Yii::app()->user->isGuest) {
$model = new Payment;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['Payment'])) {
$model->attributes = $_POST['Payment'];
$model->thoigian = date('Y-m-d H:i:s');
if ($model->save()) {
foreach ($proInfo as $key => $value) {
$order = new Order;
$order->id_sp = $key;
$order->soluong = $value;
$product = Product::model()->findByPK($key);
if (empty($product->khuyenmai)) {
$price = $product->gia_sp;
} else {
$price = ceil($product->gia_sp * (100 - $product->khuyenmai) / 100 / 1000) * 1000;
}
$order->thanhtien = $price * $value;
$order->id_payment = $model->id_hoadon;
$order->save();
}
unset(Yii::app()->session['cart']);
$this->redirect(Yii::app()->request->baseUrl . '/cart/success/' . $model->id_hoadon);
}
}
$this->render('checkout', array(
'cart' => $proInfo,
'model' => $model,
));
} else {
$model = new Payment;
$user = User::model()->findByPk(Yii::app()->user->id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['Payment'])) {
$model->attributes = $_POST['Payment'];
$model->id_user = Yii::app()->user->id;
$model->hoten = $user->hoten;
$model->email = $user->email;
$model->dienthoai = $user->dienthoai;
$model->diachi = $user->dia_chi;
$model->thoigian = date('Y-m-d H:i:s');
$model->xuly = "Chưa xử lý";
if ($model->save()) {
foreach ($proInfo as $key => $value) {
$order = new Order;
$order->id_sp = $key;
$order->soluong = $value;
$product = Product::model()->findByPK($key);
if (empty($product->khuyenmai)) {
$price = $product->gia_sp;
} else {
$price = ceil($product->gia_sp * (100 - $product->khuyenmai) / 100 / 1000) * 1000;
}
$order->thanhtien = $price * $value;
$order->id_payment = $model->id_hoadon;
$order->save();
}
unset(Yii::app()->session['cart']);
$this->redirect(Yii::app()->request->baseUrl . '/cart/success/' . $model->id_hoadon);
}
}
$this->render('checkout', array(
'user' => $user,
'cart' => $proInfo,
'model' => $model,
));
}
}
And this is my "checkout.php" file in views:
<link rel="stylesheet" type="text/css" href="<?= Yii::app()->request->baseUrl ?>/css/cart.css"/>
<?php
$this->breadcrumbs = array(
'Giỏ hàng' => array('cart/index'),
'Thanh toán'
);
$this->pageTitle = "Thanh Toán";
$items = 0;
$total = 0;
$i = 0;
?>
<h1>Thanh toán</h1>
<?php
if (empty($cart)) {
echo "<p>Bạn chưa có sản phẩm nào trong giỏ hàng</p>";
} else {
$form = $this->beginWidget('CActiveForm', array(
'id' => 'payment-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation' => false,
));
?>
<div class="payment">
<?php
if (!Yii::app()->user->isGuest) {
?>
<div class="paymentCustomer">
<h3>Thông tin thanh toán</h3>
<div style="padding: 10px; clear:both; float:left">Họ tên:<?= Yii::app()->user->name ?></div>
<div style="padding: 10px; clear:both; float:left">Email:<?= $user->email ?></div>
<div style="padding: 10px; clear:both; float:left">Địa chỉ:<?= $user->dia_chi ?></div>
<div style="padding: 10px; clear:both; float:left">Điện thoại:<?= $user->dienthoai ?></div>
</div>
<?php
} else {
?>
<div class="paymentCustomer">
<h3>Thông tin thanh toán</h3>
<div class="inputUser"><div>Họ tên <span>*</span></div><?php echo $form->textField($model, 'hoten', array('class' => "inputText loginText")); ?></div>
<?php echo $form->error($model, 'hoten'); ?>
<div class="inputUser"><div>Email <span>*</span></div><?php echo $form->textField($model, 'email', array('class' => "inputText loginText")); ?></div>
<?php echo $form->error($model, 'email'); ?>
<div class="inputUser"><div>Địa chỉ <span>*</span></div><?php echo $form->textField($model, 'diachi', array('class' => "inputText loginText")); ?></div>
<?php echo $form->error($model, 'diachi'); ?>
<div class="inputUser"><div>Điện thoại <span>*</span></div><?php echo $form->textField($model, 'dienthoai', array('class' => "inputText loginText")); ?></div>
<?php echo $form->error($model, 'dienthoai'); ?>
</div>
<?php
}
?>
<div class="paymentCustomer">
<h3>Hình thức thanh toán</h3>
<p class="paymentYour">
<?php
echo $form->radioButtonList($model, 'phuongthuc', array(
'Tại Cửa hàng' => 'Thanh toán tại cửa hàng',
'Khi Nhận hàng' => 'Thanh toán khi nhận được hàng',
'Tài khoản Ngân hàng' => 'Thanh toán qua tài khoản Ngân hàng'
), array("class" => "myCheck"));
?>
<?php echo $form->error($model, 'phuongthuc'); ?>
</p>
<h3 style="margin: 50px 0 5px 0;">Mã khuyến mãi</h3>
<?php echo $form->textField($model, 'coupon', array('class' => "inputText loginText")); ?>
<?php echo $form->error($model, 'coupon'); ?>
</div>
</div>
<div class="cartInfo">
<div class="headCart">
<div class="cartField1">Mã sản phẩm</div>
<div class="cartField2">Tên sản phẩm</div>
<div class="cartField3">Đơn giá</div>
<div class="cartField3">Số lượng</div>
<div class="cartField3">Thành tiền</div>
</div>
<?php
foreach ($cart as $key => $value) {
$product = Product::model()->findByPK($key);
if (empty($product->khuyenmai)) {
$price = $product->gia_sp;
} else {
$price = ceil($product->gia_sp * (100 - $product->khuyenmai) / 100 / 1000) * 1000;
}
?>
<div class="bodyCart">
<div class="cartField1" data-label="Mã sản phẩm"><?= $product->ma_sp ?></div>
<div class="cartField2" data-label="Tên sản phẩm"><span><?= $product->ten_sp ?></span></div>
<div class="cartField3" data-label="Đơn giá"><?= $price . "đ" ?></div>
<div class="cartField3" data-label="Số lượng"><?= $value ?></div>
<div class="cartField3" data-label="Thành tiền"><?= $price * $value . "đ" ?></div>
</div>
<?php
$items +=$value;
$total +=$price * $value;
}
?>
<div class="footCart">
<div class="cartField1">Tổng cộng</div>
<div class="cartField2"></div>
<div class="cartField3"><?= $items ?></div>
<div class="cartField3"><?= $total . "đ" ?></div>
</div>
</div>
<div>
<a href="<?= Yii::app()->request->urlReferrer ?>">
<input type="button" class="cartLeftButton button" value="Quay trở lại"/>
</a>
<?php echo CHtml::submitButton('Xác nhận và gửi đơn hàng', array("class" => "cartRightButton button")); ?>
</div>
<?php
$this->endWidget();
}
?>
But when submit that form it not direct to success page. I have try to insert die("abc") to each line in Controller and find out that it not run from the line
if($model->save()){....
How can I fix that now?