i want to create news item in codeigniter with use slug but is error display like this.
> Call to a member function insert() on a non-object in line 34
I am a newbie in Codeigniter and couldn't really figure out how to solve this.
my controller
function tambah_profil()
{
$this->data['title'] ='create a new items';
$this->form_validation->set_rules('judul', 'Judul', 'required');
$this->form_validation->set_rules('content', 'Content', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->data['contents'] = $this->load->view('admin/profil/tambah_profil', '', true);
}else{
$this->mhalaman->insert_profil();
$this->data['contents'] = $this->load->view('admin/profil/view_profil', '', true);
}
$this->data['orang'] = $this->mlogin->dataPengguna($this->session->userdata('username'));
$this->data['contents'] = $this->load->view('admin/profil/tambah_profil', '', true);
//$this->data['contents'] = 'admin/profil/tambah_profil';
$this->load->view('template/wrapper/admin/wrapper_ukm',$this->data);
}
my model
var $db;
private $tbl_halaman = 'halaman';
public function __construct()
{
parent ::__construct();
$this->load->database();
}
function get_profil($slug = FALSE)
{
if ($slug === FALSE)
{
$query = $this->db->get($this->tbl_halaman);
return $query->result_array();
}
$query = $this->db->get_where($this->tbl_halaman, array('slug'=>$slug));
return $query->row_array();
}
function insert_profil()
{
$slug = url_title($this->input->post('judul'),'dash', TRUE);
$data = array(
'judul' => $this->input->post('judul'),
'slug' => $slug,
'content' => $this->input->post('content')
);
return $this->db->insert($this->tbl_halaman ,$data); //line 34
}
please help me what to do. thank you.
Please check whether you have loaded $this->load->database() inside the model constructor.
$this->db->method_name(); will only work when the database library is loaded.
If you plan to use the database throughout your application, I would suggest adding it to your autoload.php in /application/config/.
$autoload['libraries']=array('database');
Related
Sorry for my bad english but i have a problem when i try to open localhost:8080/blog this message show up
Too few arguments to function App\Controllers\Blog::view(), 0 passed in C:\xampp\htdocs\baru\vendor\codeigniter4\framework\system\CodeIgniter.php on line 896 and exactly 1 expected
so this is the controller:
use CodeIgniter\Controller;
use App\Models\ModelsBlog;
class Blog extends BaseController
{
public function index()
{$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
if (!$this->validate([]))
{
$data['validation'] = $this->validator;
$data['artikel'] = $model->getArtikel();
return view('view_list',$data);
}
}
public function form(){
$data = [
'title' => 'Edit Form'
];
helper('form');
return view('view_form', $data);
}
public function view($id){
$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
$data['artikel'] = $model->PilihBlog($id)->getRow();
return view('view',$data);
}
public function simpan(){
$model = new ModelsBlog();
if ($this->request->getMethod() !== 'post') {
return redirect()->to('blog');
}
$validation = $this->validate([
'file_upload' => 'uploaded[file_upload]|mime_in[file_upload,image/jpg,image/jpeg,image/gif,image/png]|max_size[file_upload,4096]'
]);
if ($validation == FALSE) {
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi')
);
} else {
$upload = $this->request->getFile('file_upload');
$upload->move(WRITEPATH . '../public/assets/blog/images/');
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi'),
'gambar' => $upload->getName()
);
}
$model->SimpanBlog($data);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Simpan');
}
public function form_edit($id){
$data = [
'title' => 'edit artikel'
];
$model = new ModelsBlog();
helper('form');
$data['artikel'] = $model->PilihBlog($id)->getRow();
return view('form_edit',$data);
}
public function edit(){
$model = new ModelsBlog();
if ($this->request->getMethod() !== 'post') {
return redirect()->to('blog');
}
$id = $this->request->getPost('id');
$validation = $this->validate([
'file_upload' => 'uploaded[file_upload]|mime_in[file_upload,image/jpg,image/jpeg,image/gif,image/png]|max_size[file_upload,4096]'
]);
if ($validation == FALSE) {
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi')
);
} else {
$dt = $model->PilihBlog($id)->getRow();
$gambar = $dt->gambar;
$path = '../public/assets/blog/images/';
#unlink($path.$gambar);
$upload = $this->request->getFile('file_upload');
$upload->move(WRITEPATH . '../public/assets/blog/images/');
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi'),
'gambar' => $upload->getName()
);
}
$model->edit_data($id,$data);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Ubah');
}
public function hapus($id){
$model = new ModelsBlog();
$dt = $model->PilihBlog($id)->getRow();
$model->HapusBlog($id);
$gambar = $dt->gambar;
$path = '../public/assets/blog/images/';
#unlink($path.$gambar);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Hapus');
}
}
ModelsBlog.php :
use CodeIgniter\Model;
class ModelsBlog extends Model
{
protected $table = 'artikel';
public function getArtikel()
{
return $this->findAll();
}
public function SimpanBlog($data)
{
$query = $this->db->table($this->table)->insert($data);
return $query;
}
public function PilihBlog($id)
{
$query = $this->getWhere(['id' => $id]);
return $query;
}
public function edit_data($id,$data)
{
$query = $this->db->table($this->table)->update($data, array('id' => $id));
return $query;
}
public function HapusBlog($id)
{
$query = $this->db->table($this->table)->delete(array('id' => $id));
return $query;
}
}
And this is the view.php:
<body style="width: 70%; margin: 0 auto; padding-top: 30px;">
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2><?php echo $artikel->judul; ?></h2>
</div>
</div>
</div>
<hr>
<div class="row">
<div class="col-lg-12">
<div class="row">
<?php
if (!empty($artikel->gambar)) {
echo '<img src="'.base_url("assets/blog/images/$artikel->gambar").'" width="30%">';
}
?>
<?php echo $artikel->isi; ?>
</div>
</div>
</div>
</body>
i cant find any solutions for this error, pls help thank you very much
Let's go over what you're telling the code to do.
First, you make a call to /blog. If you have auto-routing turned on this will put you forward to the controller named 'Blog'.
class Blog extends BaseController
And since you do not extend the URL with anything, the 'index' method will be called.
public function index()
{$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
if (!$this->validate([]))
{
$data['validation'] = $this->validator;
$data['artikel'] = $model->getArtikel();
return view('view_list',$data);
}
}
The index method sets $data to an array filled with 'title' => 'artikel'. And then fills $model with a new ModelsBlog.
class ModelsBlog extends Model
There is no __construct method defined in ModelsBlog so just the class is loaded and specific execution related to $model stops there, which is fine.
Then, the index() from Blog goes on and checks whether or not $this->validate([]) returns false. Since there's no else statement, if $this->validate([]) were to return true, code execution would stop there. So we'll assume $this->validate([]) returns false. So far so good, there's nothing weird going on with your code.
However, IF $this->validate([]) returns false, you tell the index() to return the function called view(). Normally CodeIgniter would serve you the view you set as the first parameter. But since you also have a Blog method named 'view', CodeIgniter will try to reroute te request to that method. So in other words, the actual request you're trying to make is:
Blog::view()
And since you've stated that view() receives 1 mandatory parameter, the requests triggers an error. You can solve the problem by either renaming the view() method of Blog to something like 'show()' or 'read()'. Anything else that does not conflict with the native CodeIgniter view() function would be good.
Honestly though, you are sending through two parameters in the index() function call so I'm slightly confused why the error generated states you provided 0, but I hope at least you gain some insight from my answer and you manage to fix the problem.
If anyone could provide more information regarding this, feel free to comment underneath and I'll add your information to the answer (if it gets accepted).
An Error Was Encountered Unable to load the requested class:
Plugin_update_checker
I am using custom library which create a dynamic php file with 740 line code
controller function:
public function create() {
$userId=$this->session->userdata('userId');
$userName=$this->session->userdata('userName');
//Form_validation stuff
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('description', 'Description', 'required');
$this->form_validation->set_rules('requires', 'Requires', 'required');
$this->form_validation->set_rules('url', 'Homepage URL', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->index();
}else {
$data = array(
'title' => $this->input->post('title'),
'readme_text' => ($this->input->post('readme_text') == 'yes' ? 1 : 0),
'description' => $this->input->post('description'),
'requires' => $this->input->post('requires'),
'url' => prep_url($this->input->post('url')),
'user_id' => $userId
);
$insert_id = $this->model->insert_data($data);
print ($insert_id);
if ($insert_id) {
$this->session->set_userdata('pluginId', $insert_id);
$key = substr(number_format(time() * rand(),0,'',''),0,6).$insert_id;
//$this->model->update_data(array('plugin_id' => $insert_id), array('secret_key' => $key,'php_file' => $WinnRepoPluginUpdater));
$this->load->library('RepositoryHelper');
// ------------------------Can't Load this Library ---------------------
$this->load->library('Plugin_update_checker');
// --------------------------------------------------------------------
$repo= new RepositoryHelper();
$php_code = new plugin_update_checker();
$dir = 'api/'.$repo->sum($userId,1548).'-'.$repo->slug($userName).'/plugins/';
$file_name = 'WinnRepo'.$repo->slug_space($data['title']).'PluginUpdater_'.$key;
$WinnRepoPluginUpdater = $dir.'/'.$file_name.'.php';
$repo->make_directory($dir);
$url = base_url().'home/plugin_version_control/';
//$code = $php_code->plugin_update_checker('WinnRepo_'.$key, $file_name, 'WinnRepoPluginUpdateChecker_2_1', $url, $key);
$repo->make_file($WinnRepoPluginUpdater,'ccccccccccc');
$this->model->update_data(array('plugin_id' => $insert_id), array('secret_key' => $key,'php_file' => $WinnRepoPluginUpdater));
redirect('Plugins/view');
}
}
}
Here is custom Library:
class Plugin_update_checker
{
public function plugin_update_checker($winnRepo, $className, $PluginUpdateChecker_2_1, $url, $licence_key)
{
echo '<?php ';
?>
// Here 740 line which is auto generated a php file
<?php
}
}
Library name: /application/libraries/Plugin_update_checker.php
Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Plugin_update_checker
{
function __construct()
{
$this->ci =& get_instance();
}
function test(){
return 'test';
}
}
Controller Code:
public function index()
{
$this->load->library('Plugin_update_checker');
echo $this->plugin_update_checker->test();
}
Try this! This code work for me.
I have a codeigniter form which runs some basic validation and submits data to the database. But I want to additionally alter the post data of one of the fields to use the inflector helper in order to convert the posted data to camel case before submitting to the database. How do I do this?
Here is my current form:
<?php echo form_open('instances/create') ?>
<label for="content">Content</label>
<textarea name="content"></textarea><br />
<input type="submit" name="submit" value="Create" />
</form>
Here is my current controller:
public function create(){
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->helper('inflector');
$data['title'] = 'Create an instance';
$this->form_validation->set_rules('title', 'Title', 'required');
//want to camelize the 'title' here
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('instances/create');
$this->load->view('templates/footer');
}
else
{
$this->instances_model->set_instances();
$this->load->view('instances/success');
}
}
and here's my model:
<?php
class Instances_model extends CI_Model {
public function __construct(){
$this->load->database();
}
public function get_instances($slug = FALSE){
if ($slug === FALSE){
$query = $this->db->get('extra_instances');
return $query->result_array();
}
$query = $this->db->get_where('extra_instances', array('slug' => $slug));
return $query->row_array();
}
public function set_instances(){
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
'slug' => $slug,
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'year' => $this->input->post('year'),
'credit' => $this->input->post('credit'),
'source' => $this->input->post('source')
);
return $this->db->insert('extra_instances', $data);
}
}
I know that you can camelize a variable with the following:
echo camelize('my_dog_spot'); // Prints 'myDogSpot'
and I know that you can run custom validation like this:
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
public function username_check($str)
{
if ($str == 'test')
{
$this->form_validation->set_message('username_check', 'The {field} field can not be the word "test"');
return FALSE;
}
else
{
return TRUE;
}
}
But I'm lacking the knowledge of how to put this altogether to quickly change the POST data before submitting to the database.
Nothing too complicated, you can do it after you pass the validation, just before inserting your data array into the database:
$data = array(
'slug' => $slug,
'title' => camelize($this->input->post('title')),
// ...
public function addcategory() {
$this->load->model('product_model');
$new_category = $this->product_model->add_category($this->input->post());
if ($new_category) {
$info = array(
'message' => 'Data Saved sucess',
'value' => TRUE
);
$this->index($info);//not working
}
$this->index($info);//working without $info
}
here i need to call $this->index($info); within the if(){} but it is not working... however when i put this code outside if() it works but i cant pass $info variable via $this->index($info);
I call the function($this->index($info);) in side if then function not working at all. But if i used function outside if its get call but giving an error 'Undefined index: info'.
How to call the index() function??
Declare $info outside the if statement should work.
Then use the index function outside the statement.
public function addcategory() {
$info = null;
$this->load->model('product_model');
$new_category = $this->product_model->add_category($this->input->post());
if ($new_category) {
$info = array(
'message' => 'Data Saved sucess',
'value' => TRUE
);
}
$this->index($info);//working without $info
}
Solution1:
You can use Redirect method to redirect on index :
$this->session->set_flashdata('info', $info);
redirect('/controller_name/index');
And get the info on index method :
$info = $this->session->flashdata('info');
Solution2:
Add this Remap Function to your controller :
public function _remap($method)
{
if ($method == 'some_method')
{
$this->$method();
}
else
{
$this->index();
}
}
Your if statement is not doing anything with the variable $new_category
try.
if (isset($new_category) && !empty($new_category)) // check for the existence and value
{
$info = array(
'message' => 'Data Saved sucess',
'value' => TRUE
);
$this->index($info);
}
else
{
$info = array(
'message' => 'unsuccessful data entry',
'value' => FALSE
);
}
I was playing around with this code. http://programmersvoice.com/tag/code
And I noticed that the following line.
$this->load->model($this->models."pagemodel", 'pages');
I compare this with
$this->load->model("pagemodel", 'pages');
This is what codeigniter's document http://codeigniter.com/user_guide/general/models.html#loading suggest.
However method 2 takes longer time than the first one.
Could anyone explain what "$this->models." do please?
Thanks in advance.
The following is the whole code of pages.php in controllers/admin
<?php
class Pages extends Application
{
function Pages()
{
parent::Application();
$this->auth->restrict('editor'); // restrict this controller to editor and above
$this->load->model($this->models."pagemodel", 'pages'); // Load the page model
}
function manage()
{
$data = $this->pages->pages(); // List the pages
$this->table->set_heading('Title', 'Slug', 'Actions'); // Setting headings for the table
foreach($data as $value => $key)
{
$actions = anchor("admin/pages/edit/".$key['id']."/", "Edit") . anchor("admin/pages/delete/".$key['id']."/", "Delete"); // Build actions links
$this->table->add_row($key['title'], $key['slug'], $actions); // Adding row to table
}
$this->auth->view('pages/manage'); // Load the view
}
function delete($id)
{
$this->pages->delete($id);
$this->auth->view('pages/delete_success');
}
function add()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Page Title', 'required');
$this->form_validation->set_rules('content', 'Content', 'required');
if($this->form_validation->run() == FALSE)
{
$this->auth->view('pages/add');
}
else
{
$data['title'] = set_value('title');
$data['content'] = set_value('content');
$data['slug'] = url_title($data['title'], 'underscore', TRUE);
$this->pages->add($data);
$this->auth->view('pages/add_success');
}
}
function edit($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Page Title', 'required');
$this->form_validation->set_rules('content', 'Content', 'required');
if($this->form_validation->run() == FALSE)
{
$data = $this->pages->page($id);
$this->auth->view('pages/edit', $data[0]);
}
else
{
$data['title'] = set_value('title');
$data['content'] = set_value('content');
$data['slug'] = url_title($data['title'], 'underscore', TRUE);
$this->pages->edit($id, $data);
$this->auth->view('pages/edit_success');
}
}
}
?>
I'm not totally sure about the following, since the current version of Codeigniter doesn't seem to populate the $this->models variable, but I think that:
$this->models contained the full path to the application models directory, and therefore loading is faster, since CI doesn't have to look in different folders (global & application)