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')),
// ...
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).
I am trying to update a mySQL table while using CodeIgniter.
The Controller
I have the redirect() commented out to use print_r(). When it returns the array, it returns the correct updated values. But if i uncomment the redirect, then it will redirect me to the page with the table and the values will not get updated. I also check on phpMyAdmin to make sure values arent getting updated and not just displaying, but they arent updating on their either. This is confusing me because the print_r() is returning the correct values.
<?php
class update_ctrl extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('update_model');
}
public function updateGame($id){
$this->load->model('update_model');
$data['games'] = $this->update_model->getGame($id);
$this->load->view('update_view', $data);
$this->load->view('footer');
}
public function update(){
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('genre', 'Genre', 'trim|required');
$this->form_validation->set_rules('developer', 'Developer', 'trim|required');
$this->form_validation->set_rules('year', 'YearReleased', 'trim|required|numeric');
$this->form_validation->set_rules('price', 'Price', 'trim|required|numeric');
$id = $this->input->post('ID');
$data = array(
'Name' => $this->input->post('name'),
'Genre' => $this->input->post('genre'),
'Developer' => $this->input->post('developer'),
'YearReleased' => $this->input->post('year'),
'Price' => $this->input->post('price')
);
$this->load->model('update_model');
$this->update_model->update($id, $data);
$this->session->set_flashdata('msg', 'Game Updated!');
print_r($data);
//redirect('');
}
}
?>
The Model
<?php
class update_model extends CI_Model {
public function getGame($id) {
$this->db->select('*');
$this->db->from('games');
$this->db->where('ID', $id);
$query = $this->db->get();
if ($query->num_rows() > 0){
return $query->result();
} else {
return $query->result();
}
}
public function update($id, $data){
$this->db->where('ID', $id);
$this->db->update('games', $data);
}
}
?>
The only thing I can think of is that your query is silently failing. Go into database.php and change db_debug to TRUE and run everything again.
I would also like to add that you seem to do a good job making sure all your fields are validated. I'd also add a validation for id just to make sure you are getting it - in the case the user does something funky then they won't get some weird query error because the id wasn't set.
Comment out your all $this->form_validation->set_rules and try again, I think the numeric validation get errors
public function update(){
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
//$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
//$this->form_validation->set_rules('name', 'Name', 'trim|required');
//$this->form_validation->set_rules('genre', 'Genre', 'trim|required');
//$this->form_validation->set_rules('developer', 'Developer', 'trim|required');
//$this->form_validation->set_rules('year', 'YearReleased', 'trim|required|numeric');
//$this->form_validation->set_rules('price', 'Price', 'trim|required|numeric');
$id = $this->input->post('ID');
$data = array(
'Name' => $this->input->post('name'),
'Genre' => $this->input->post('genre'),
'Developer' => $this->input->post('developer'),
'YearReleased' => $this->input->post('year'),
'Price' => $this->input->post('price')
);
$this->load->model('update_model');
$this->update_model->update($id, $data);
$this->session->set_flashdata('msg', 'Game Updated!');
print_r($data);
//redirect('');
}
}
I've never used a PHP framework, but I wanted to learn how to use one so I could more easily program for my company, so I chose CodeIgniter.
I am following the code igniter tutorial for a news section so I could learn how things work - but I am having some issues/questions.
Now, I am to the point in the tutorial that I have a form that submits and takes me to a success page. In normal PHP this is where I would just redirect the page to the view page of the news item submitted. In CodeIgniter I have a view function in my controller here
public function view($slug = NULL)
{
$data['news_item'] = $this->news_model->get_news($slug);
if (empty($data['news_item']))
{
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('templates/footer');
}
I'm not sure how to get the slug from the form when it is submitted.
Here is my create function (Basically the one that inserts the database info and redirects to news/success)
public function create()
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Create a news item';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'Text', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('news/create');
$this->load->view('templates/footer');
}
else
{
$this->news_model->set_news();
$this->load->view('news/success');
}
}
But I want this to redirect to the view page. To do that I need to have the slug I believe. So it should redirect to news/view/$slug - but I'm not sure how to do this.
My set_news model:
public function set_news()
{
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
You should use something like that:
redirect('news/view/'.url_title($this->input->post('title'), 'dash', TRUE));
I am using codeigniter. I have multiple forms but only after I reach the last form I need a submit action which should insert all the data from all forms. How to do this?
I have a controller file.
<?php
class Admin_service extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('service_model');
if(!$this->session->userdata('is_logged_in')){
redirect('admin/login');
}
}
public function add1()
{
if ($this->input->server('REQUEST_METHOD') === 'POST')
{
$this->load->library('session');
$this->session->unset_userdata('service_detail');
$this->form_validation->set_rules('backbar', 'backbar');
$this->form_validation->set_error_delimiters('<div class="alert alert-error"><a class="close" data-dismiss="alert">×</a><strong>', '</strong></div>');
//if the form has passed through the validation
if ($this->form_validation->run())
{
$data_to_store = array(
'id' => $this->input->post('service_detail'),
'service_name' => $this->input->post('backbar')
);
if($this->service_model->store_service($data_to_store)){
$data['flash_message'] = TRUE;
$this->session->set_flashdata('flash_message', 'updated');
}else{
$data['flash_message'] = FALSE;
}
}
}
$data['category'] = $this->category_model->get_category();
$data['main_content'] = 'admin/service/add1';
$this->load->view('includes/template', $data);
}
public function add()
{
if ($this->input->server('REQUEST_METHOD') === 'POST')
{
$this->load->library('session');
$this->session->unset_userdata('service_detail');
$this->form_validation->set_rules('id', 'id');
$this->form_validation->set_rules('service_name', 'service_name','alpha');
$this->form_validation->set_rules('category', 'category');
$this->form_validation->set_rules('service_tax', 'service_tax');
$this->form_validation->set_rules('service_length', 'service_length','numeric');
$this->form_validation->set_rules('service_price', 'service_price','numeric');
$this->form_validation->set_error_delimiters('<div class="alert alert-error"><a class="close" data-dismiss="alert">×</a><strong>', '</strong></div>');
if ($this->form_validation->run())
{
$data_to_store = array(
'id' => $this->input->post('id'),
'service_name' => $this->input->post('service_name'),
'category' => $this->input->post('category'),
'service_tax' => $this->input->post('service_tax'),
'service_length' => $this->input->post('service_length'),
'service_price' => $this->input->post('service_price')
);
if($this->service_model->store_service($data_to_store)){
$data['flash_message'] = TRUE;
$this->session->set_flashdata('flash_message', 'updated');
$this->session->set_userdata('service_detail', ['service_price'=>$this->input->post('service_price'),"service_tax"=>$this->input->post('service_tax')]);
redirect(base_url().'admin/service/view');
}else{
$data['flash_message'] = FALSE;
}
}
}
$data['main_content'] = 'admin/service/add';
$this->load->view('includes/template', $data);
}
}
Here I have two functions add and add1 each loads a separate view where I have my form. After the add form I need to get data from the add1 form and insert in single table when I click submit button in second form. How to do it? Can some one help me code?
Add one checkbox on html page where user submits form:
<input type="checkbox" name="is_finish" value="1" />
in your controller modify code in if ($this->form_validation->run()) condition as below:
if ($this->form_validation->run())
{
$this->load->library('session');
$service_details[] = array(
'id' => $this->input->post('id'),
'service_name' => $this->input->post('service_name'),
'category' => $this->input->post('category'),
'service_tax' => $this->input->post('service_tax'),
'service_length' => $this->input->post('service_length'),
'service_price' => $this->input->post('service_price')
);
$service_details_sess = $this->session->userdata('service_details');
if($service_details_sess != "") {
$service_details[] = $service_details_sess;
}
$this->session->set_userdata('service_details',$service_details);
$finish = $this->input->post('is_finish');
if($finish == "1")
{
$this->service_model->store_service($service_details);
}
}
modify store_service function on service_model model as below:
function store_service($service_details) {
$this->load->library('session');
$this->session->unset_userdata('service_details');
$this->db->insert_batch($service_details);
if ($this->db->affected_rows() > 0)
{
return TRUE;
}
return FALSE;
}
HTML part:
<button id="store_data" type="button">Store</button>
<script type="text/javascript">
$("#store_data").click(function(event) {
$.ajax({
url: 'path to your controller that store data',
type: 'POST',
data: $("#your_form_id").serialize(),
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
</script>
I am currently trying to add data to the database using codeigniter. I have already set up a registration page using the active method and attempted to use the same method for the add news form but was unsuccessful.
When I click submit it is saying page cannot be found and the url shows the controller function name. This is the same when i purposely leave any fields blank. I have checked my database and no records have been added and no php log errors.
Here is my snippets of code:
View:
<?php echo form_open('add/add_article'); ?>
<?php echo form_input('title', set_value('title', 'Title')); ?><br />
<?php echo form_textarea('content', set_value('content', 'Content')); ?><br />
<?php echo form_input('author', set_value('author', 'Author')); ?>
<?php echo form_submit('submit', 'Add Article'); ?>
<?php echo validation_errors('<p class="error">' );?>
<?php echo form_close(); ?>
Controller:
class Add extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->load->view('admin/add');
}
public function add_article() {
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'trim|required');
$this->form_validation->set_rules('content', 'Content', 'trim|required');
$this->form_validation->set_rules('author', 'Author', 'trim|required');
if($this->form_validation->run() == FALSE) {
$this->index();
}else{
$this->load->model('news_model');
if($query = $this->news_model->addArticle()) {
$this->load->view('news');
}else {
$this->load->view('news');
}
}
}
}
Model:
public function __construct() {
parent::__construct();
}
function addArticle() {
$data =array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'author' => $this->input->post('author'),
'username' => $this->input->post('username'));
$insert = $this->db->insert('news', $data);
return $insert;
}
}
If it's the server that's throwing the page not found it's almost certainly a URL issue as opposed to a CI/PHP issue.
Is your base url defined properly in the config file? Is your .htaccess configured properly (an old configuration could be routing /add requests away from CI)?
Try adding the following action to the Add controller, and navigating to it directly at http://[base]/add/thetest
public function thetest() {
echo 'Controller accessed';
die;
}
If it still says page not found it's not your code, it's your config (either server config or CI).
Instead of insert use update in your model like:
$insert = $this->db->update('news', $data);
return $insert;
And I think that this part of your code in controller is wrong too (wrong if statement and no data send to model):
if($query = $this->news_model->addArticle()) {
$this->load->view('news');
}else {
$this->load->view('news');
}
try this:
$data =array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'author' => $this->input->post('author'),
'username' => $this->input->post('username')
);
$query = $this->news_model->addArticle($data);
if($query)
{
// query ok
$this->load->view('news');
}
else {
// no query
$this->load->view('news');
}