Codeigniter MVC Sample Code - codeigniter

Hi
I am following the getting started guide for Codeigniterr given at http://www.ibm.com/developerworks/web/library/wa-codeigniter/
I have followed the instruction to create the front view and added controller to handle form submission. Ideally, when i submit the form, it should load the model class and execute the function to put details on the database, but instead it is just printing out the code of the model in the browser.
**Code of view (Welcome.php)**
----------------
<?php
class Welcome extends Controller {
function Welcome()
{
parent::Controller();
}
function index()
{
$this->load->helper('form');
$data['title'] = "Welcome to our Site";
$data['headline'] = "Welcome!";
$data['include'] = 'home';
$this->load->vars($data);
$this->load->view('template');
}
function contactus(){
$this->load->helper('url');
$this->load->model('mcontacts','',TRUE);
$this->mcontacts->addContact();
redirect('welcome/thankyou','refresh');
}
function thankyou(){
$data['title'] = "Thank You!";
$data['headline'] = "Thanks!";
$data['include'] = 'thanks';
$this->load->vars($data);
$this->load->view('template');
}
}
/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */
**Code of Model**
--------------
class mcontacts extends Model{
function mcontacts(){
parent::Model();
}
}
function addContact(){
$now = date("Y-m-d H:i:s");
$data = array(
'name' => $this->input->xss_clean($this->input->post('name')),
'email' => $this->input->xss_clean($this->input->post('email')),
'notes' => $this->input->xss_clean($this->input->post('notes')),
'ipaddress' => $this->input->ip_address(),
'stamp' => $now
);
$this->db->insert('contacts', $data);
}
**OUTPUT after clicking submit**
-----------------------------
class mcontacts extends Model{ function mcontacts(){ parent::Model(); } } function addContact(){ $now = date("Y-m-d H:i:s"); $data = array( 'name' => $this->input->xss_clean($this->input->post('name')), 'email' => $this->input->xss_clean($this->input->post('email')), 'notes' => $this->input->xss_clean($this->input->post('notes')), 'ipaddress' => $this->input->ip_address(), 'stamp' => $now ); $this->db->insert('contacts', $data); }
I have tried doing these things
1. Making all PHP codes executable
2. Change ownership of files to www-data
3. make permission 777 for whole of www
But, the code of model seems to be just printed ... PLEASE HELP

Just a few minor points that might help you:
In your controller, point the index method at the method you would like to call on that page. For example:
function index()
{
$this->welcome();
}
That will help keep things clean and clear, especially if anyone else comes in to work on the code with you later. I chose welcome because that's the name of your controller class and that will keep things simple.
In your model, this:
class mcontacts extends Model{
Should be:
class Mcontacts extends Model{
Capitalize those class names! That could be giving you the trouble you describe.
See here for more info on this: http://codeigniter.com/user_guide/general/models.html
Don't use camel case in your class or method names. This isn't something that will cause your code to fail, but it's generally accepted practice. See Codeigniter's PHP Style guide for more information on this: http://codeigniter.com/user_guide/general/styleguide.html

It's difficult to see with the formatting as it is, but do have an extra curly brace after the constructor method (mcontacts()) in the model? This would cause problems! Also although the code looks generally ok, there are probably better ways to use the framework especially if you do anything more complicated than what you've shown. For example, autoloading, form validation etc. Can I suggest you have a read of the userguide? It's very thorough and clear and should help you alot. http://codeigniter.com/user_guide/index.html

Related

Laravel Livewire The POST method is not supported for this route

As soon as I inserted this title the system showed me all the similar questions, and none of them help me. I get this error "The POST method is not supported for this route." no matter what I try. Even worse, is I already made another component with the identical logic, and that one works good.
here are the routes: (teeoffform works, bulletin does not)
Route::get('/bulletin', function () {
return view('bulletin');
});
Route::get('/teeoffform', function () {
return view('teeoffform');
});
Here are the form tags: both identical one works one doesn't
<form wire:submit.prevent="submit" method="POST">
this is my component from the one that doesn't work (bulletin)
the only difference from the other one that does work, is that there is no rendering method, so I tried to take it out and see if that was the problem, but no luck... I thought, since my route is alrady calling a view maybe the conflict is there... but it doesn't matter, I get the error anyways, and I'm out of ideas.
<?php
namespace App\Http\Livewire;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use App\Models\Bulletins;
use App\Models\User;
class Bulletin extends Component
{
public $title;
public $message;
public $messagesending;
public $user_email;
public $userTable_email;
public $expires;
public $success_message;
protected $rules = [
'title' => 'required',
'message' => 'required',
'user_email' => 'required',
'expires' => 'required',
];
public function render()
{
return view('livewire.bulletin', ['email_data' => User::orderBy('email','asc')->get()]);
}
public function submit()
{
$this->validate();
$sendMessage = new Bulletins;
$sendMessage->title = $this->title;
$sendMessage->message = $this->messagesending;
$sendMessage->user_email = $this->user_email;
$sendMessage->expires = $this->expires;
$sendMessage->save();
$this->success_message = 'Message Sent Successfully';
}
}
I really don't get it... I looked for 4 hours now why this is happening.
I ran into this issue as well and found that I was not including the Livewire styles and scripts in my apps layouts blade files.
#livewireStyles
#livewireScripts
I found the difference, not in the logic of the code, but where I was running it from. If I was testing from (localhost/bulletin) I was getting that error. if I included the component inside the dashboard (localhost/home) and ran it from there, then everything worked...
why is that? I can't go to (localhost/bulletin) without being logged in, so I was logged in.

Magento Form with Tabs Fieldset Issue

I'm writing a custom Magento module for my store and I'm facing a weird issue with a fieldset in one form. The form is assigned to a tab, however the fieldset starts from the top of container, not from just below buttons area. Please see the image attached
I want it to display like:
This module is being developed on Magento 1.9.0.1 without any modification whatsoever, just the demo data.
Below is the code for all the classes:
Controller:
added form container and tabs to left column
class Koala_Socialmanager_Adminhtml_TwitterController extends Mage_Adminhtml_Controller_Action {
public function directTweetAction(){
$this->loadLayout();
$this->_addContent($this->getLayout()->createBlock('koala_socialmanager/twitter_directTweet_tweet','directTweet'))
->_addLeft($this->getLayout()->createBlock('koala_socialmanager/twitter_directTweet_edit_tabs'));
$this->renderLayout();
Form container:
class Koala_Socialmanager_Block_Twitter_DirectTweet_Tweet extends Mage_Adminhtml_Block_Widget_Form_Container {
public function __construct()
{
$this->_blockGroup = 'koala_socialmanager';
$this->_controller = 'twitter_directTweet';
$this->_headerText = Mage::helper('koala_socialmanager')->__('Direct Tweets');
parent::__construct();
$this->_updateButton('save', 'label', Mage::helper('adminhtml')->__('Tweet Now!'));
}
}
Tabs:
class Koala_Socialmanager_Block_Twitter_DirectTweet_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs{
public function __construct(){
parent::__construct();
$this->setId('tweetTabs');
$this->setDestinationElementId('edit_form');
$this->setTitle(Mage::helper('koala_socialmanager')->__('Twitter'));
}
public function _beforeToHtml(){
$this->addTab('form_section_form',array(
'label' => Mage::helper('koala_socialmanager')->__("Tweet"),
'title' => Mage::helper('koala_socialmanager')->__("Tweet"),
'content' => $this->getLayout()->createBlock('koala_socialmanager/twitter_directTweet_edit_tabs_form')->initForm()->toHtml(),
'active' => true
));
$this->addTab('form_section_external_media',array(
'label' => Mage::helper('koala_socialmanager')->__("External Media"),
'title' => Mage::helper('koala_socialmanager')->__("External Media"),
'content' => $this->getLayout()->createBlock('koala_socialmanager/twitter_directTweet_edit_tabs_externalMedia')->initForm()->toHtml()
));
$this->addTab('form_section_magento_media',array(
'label' => Mage::helper('koala_socialmanager')->__("Magento Product Media"),
'title' => Mage::helper('koala_socialmanager')->__("Magento Product Media"),
'content' => $this->getLayout()->createBlock('koala_socialmanager/twitter_directTweet_edit_tabs_magentoProductMedia')->toHtml()
));
return parent::_beforeToHtml();
}
}
And form with fieldset:
class Koala_Socialmanager_Block_Twitter_DirectTweet_Edit_Tabs_Form extends Mage_Adminhtml_Block_Widget_Form {
public function __construct()
{
parent::__construct();
}
public function initForm(){
$form = new Varien_Data_Form();
$this->setForm($form);
$form->setHtmlIdPrefix('socialmanager');
$helper = Mage::helper('koala_socialmanager');
$fieldset = $form->addFieldset('base_fieldset', array(
'legend' => Mage::helper('koala_socialmanager')->__('Tweeter Message')
));
$fieldset->addField('statusUpdate', 'textarea', array(
'name'=>'tweet',
'label'=>$helper->__("Tweet this Message:"),
'after_element_html'=>'<div class="characterCounter">0</div>'
));
Mage::helper('koala_socialmanager')->getTwitterFormScript();
return $this;
I believe I'm missing something silly. Any help appreciated.
Cheers
Paul
I've solved the problem, still don't know the cause though. I simply rewritten everything to another folder changing the class names, created another action in controller called testAction, so all files from DirectTweet folder are located in Message folder, and guess what? when you display that form from testActoin it works as it should, when I display the old form from DirectTweet folder - fieldset is broken.
I have magento cache disabled all the time, I cleared all tmp, cache, session folders, cleared browser cache and had no luck with fixing it, so I'm wondering why the new "version" works even though there is no changes to the code apart from cosmetic ones (removing empty lines, or changed text for labels/headers).
For the last 20 minutes I was comparing file by file in phpstorm, and seriously no differences apart from class names and texts to output.... I'm to tired to think about it anymore.
Below desired output :)
Happy New Year
Paul

Laravel 4 Framework - Query scope not working

Im a big 'ol newbie at Laravel, and im trying to do a query scope but it doesnt seem to be working, i keep getting this error
Argument 1 passed to Letters::scopeForUser() must be an instance of User
My user IS logged in, but it still doesnt seem to be working.
This is my Letters model
<?php
class Letters extends Eloquent {
protected $table = 'letters';
public function scopeForUser(User $u)
{
return $query->where('userid', '=', $u->id);
}
}
and in my controller i have the following
Route::get('myletters', array(
'before' => 'auth|userdetail',
function()
{
// Grab the letters, if any, for this user
$letters = Letters::forUser(Auth::user())->get();
$data = [
'letters' => $letters
];
return View::make('myletters', $data);
}
));
Any help would be greatly appreciated.
Cheers
You should pass a variable $query as the first argument to your method in the Model. For example:
public function scopeForUser($query, User $u)
{
return $query->where('userid', '=', $u->id);
}
The first argument doesn't necessarily need to be $query, but it should be the same variable that you are using inside the scope method ($query in this case).

codeigniter best way to create controller for editing a db row

Im new to codeigniter and im developing my first web application with it and want to make sure im doing best practices the 1st time so i dont have to go back to make corrections down the road. with that said, here is what im doing.
I want to edit a note in the DB, then after the record has been updated redirect to a different page.
my model is coded correctly so im not worried there, but the controller looks like this (and this is probably not correct:
public function edit($id) {
$this->load->model('Notes_model');
if (isset($_POST["edit"]))
{
$data['data'] = $this->Notes_model->edit($id);
$url = "/Notes/view/" . $id;
redirect($url);
}
$data['notes'] = $this->Notes_model->viewNotes($id);
$this->load->view('templates/header');
$this->load->view('notes/edit', $data);
$this->load->view('templates/footer');
}
hopefull this makes sense, basically what I'm wanting to do here is:
1.) Show the edit note page
2.) if i edited that page by hitting submit
a.) update the db
b.) redirect to a different page.
does this look pretty good or should i make some better changes?
Although your controller code is fine but one thing you have to take care that you should load model in the constructor of your controller so you don't have to include the model in each function same recommendations for the libraries, helpers this is the best practice
class myclass extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('Notes_model');
$this->load->helper(form);
}
public function myfunction(){
}
}
Here is the starting tutorial with MVC standards advanced-codeigniter-techniques-and-tricks
<?php
class Home extends CI_Controller
{
function __construct() {
parent::__construct();
$this->m_auth->notLogin();
$this->load->library('form_validation');
$this->load->library('ajax_pagination');
$this->load->library('dateconverter');
$this->load->helper('template');
$this->load->helper('check');
$this->load->model('mymodels/crud_model');
$this->lang->load('personal', $this->m_auth->get_language());
$this->lang->load('global', $this->m_auth->get_language());
}
function index()
{
$this->get_recs();
}
function get_recs()
{
//get for view or first page to be showed
}
/**
* Register New User
*/
function updateRecords()
{
$this->form_validation->set_rules('ministery','<span class="req">(Ministry)</span>','trim|required');
$this->form_validation->set_rules('directorate','<span class="req">(Directorate)</span>','trim|required');
if($this->form_validation->run()==FALSE)
{
header_tpl($this->m_auth->get_language(),'a');
banner_tpl($this->m_auth->get_language(),'a');
left_tpl($this->m_auth->get_language(),'a');
$content = $this->load->view('personal/edit_personal', $this->POST,true);
content_tpl($content);
footer_tpl();
}
else
{
$form_data = array(
'ministry' => $this->input->post('ministery'),
'directorate' => $this->input->post('directorate'),
'job_province' => $this->input->post('job_province'),
'job_district' => $this->input->post('job_district'),
'first_name' => $this->input->post('fname'),
'last_name' => $this->input->post('lname')
);
if($this->crud_model->update_recs('ast_emp_property',$form_data)==TRUE)
{
$this->session->set_flashdata("msg","<span class='m_success'>".$this->lang->line('global_insert_success')."</span>");
redirect('/home/success_reg/'.$id.'','refresh');
}
else
{
$this->session->set_flashdata("msg","<span class='m_error'>".$this->lang->line('global_insert_error')."</span>");
redirect('home','refresh');
}
}
}
}
?>

cannot set user data in session codeigniter

please look at this.
The code below is from my model class (using datamapper orm)
function login()
{
$u = new User();
$u->where('username', $this->username)->get();
$this->salt = $u->salt;
$this->validate()->get();
if (empty($this->id))
{
// Login failed, so set a custom error message
$this->error_message('login', 'Username or password invalid');
return FALSE;
}
else
{
// Login succeeded
$data = array
(
'username' => $u->username,
'usergroup' => $u->usergroup->get(),
'is_logged_in' => true
);
$this->session->set_userdata($data);
return TRUE;
}
}
when i do this i get
**Fatal error: Call to a member function set_userdata() on a non-object**
but when i do this instead
$data = array
(
'username' => $u->username,
'usergroup' => $u->usergroup->get(),
'is_logged_in' => true
);
$obj=& get_instance();
$obj->session->set_userdata($data);
It works.
Please what is the right way to get this working ?
Thanks in advance.
your model did not extends CI_Model
after that you have to add constructor to your model
add this code to yours
function __construct()
{
parent::__construct();
$this->load->library('session');
}
Well, you didn't provide enough information.
The first code looks fine, provided that:
You actually load the session class before calling it (you also need to create an encryption key in your configs).
$this->load->library('session');
$this->session->set_userdata($data);
The above code, or your code, is inside a controller, a model or a view.
$this relates to the CI's superclass, in particular to an instance of the Session class, so if you're calling that inside a helper (collection of functions), or inside a library (where you need to create a CI instance first), it won't work.

Resources