Create news items

You now know how you can read data from a database using CodeIgniter, butyou haven’t written any information to the database yet. In this section,you’ll expand your news controller and model created earlier to includethis functionality.

Create a form

To input data into the database, you need to create a form where you caninput the information to be stored. This means you’ll be needing a formwith two fields, one for the title and one for the text. You’ll derivethe slug from our title in the model. Create a new view atapp/Views/news/create.php.

  1. <h2><?= esc($title); ?></h2>
  2.  
  3. <?= \Config\Services::validation()->listErrors(); ?>
  4.  
  5. <form action="/news/create">
  6.  
  7. <label for="title">Title</label>
  8. <input type="input" name="title" /><br />
  9.  
  10. <label for="body">Text</label>
  11. <textarea name="body"></textarea><br />
  12.  
  13. <input type="submit" name="submit" value="Create news item" />
  14.  
  15. </form>

There is only one thing here that probably look unfamiliar to you: the\Config\Services::validation()->listErrors() function. It is used to reporterrors related to form validation.

Go back to your News controller. You’re going to do two things here,check whether the form was submitted and whether the submitted datapassed the validation rules. You’ll use the formvalidation library to do this.

  1. public function create()
  2. {
  3. helper('form');
  4. $model = new NewsModel();
  5.  
  6. if (! $this->validate([
  7. 'title' => 'required|min_length[3]|max_length[255]',
  8. 'body' => 'required'
  9. ]))
  10. {
  11. echo view('templates/header', ['title' => 'Create a news item']);
  12. echo view('news/create');
  13. echo view('templates/footer');
  14.  
  15. }
  16. else
  17. {
  18. $model->save([
  19. 'title' => $this->request->getVar('title'),
  20. 'slug' => url_title($this->request->getVar('title')),
  21. 'body' => $this->request->getVar('body'),
  22. ]);
  23. echo view('news/success');
  24. }
  25. }

The code above adds a lot of functionality. The first few lines load theform helper and the NewsModel. After that, the Controller-provided helperfunction is used to validate the $_POST fields. In this case, the title andtext fields are required.

CodeIgniter has a powerful validation library as demonstratedabove. You can read more about this libraryhere.

Continuing down, you can see a condition that checks whether the formvalidation ran successfully. If it did not, the form is displayed; if itwas submitted and passed all the rules, the model is called. Thistakes care of passing the news item into the model.This contains a new function, url_title(). This function -provided by the URL helper - strips downthe string you pass it, replacing all spaces by dashes (-) and makessure everything is in lowercase characters. This leaves you with a niceslug, perfect for creating URIs.

After this, a view is loaded to display a success message. Create a view atapp/Views/news/success.php and write a success message.

This could be as simple as::

  1. News item created successfully.

Model Updating

The only thing that remains is ensuring that your model is set upto allow data to be saved properly. The save() method that wasused will determine whether the information should be insertedor if the row already exists and should be updated, based on the presenceof a primary key. In this case, there is no id field passed to it,so it will insert a new row into it’s table, news.

However, by default the insert and update methods in the model willnot actually save any data because it doesn’t know what fields aresafe to be updated. Edit the model to provide it a list of updatablefields in the $allowedFields property.

  1. <?php namespace App\Models;
  2. use CodeIgniter\Model;
  3.  
  4. class NewsModel extends Model
  5. {
  6. protected $table = 'news';
  7.  
  8. protected $allowedFields = ['title', 'slug', 'body'];
  9. }

This new property now contains the fields that we allow to be saved to thedatabase. Notice that we leave out the id? That’s because you will almostnever need to do that, since it is an auto-incrementing field in the database.This helps protect against Mass Assignment Vulnerabilities. If your model ishandling your timestamps, you would also leave those out.

Routing

Before you can start adding news items into your CodeIgniter applicationyou have to add an extra rule to app/Config/Routes.php file. Make sure yourfile contains the following. This makes sure CodeIgniter sees ‘create’as a method instead of a news item’s slug.

  1. $routes->match(['get', 'post'], 'news/create', 'News::create');
  2. $routes->get('news/(:segment)', 'News::view/$1');
  3. $routes->get('news', 'News::index');
  4. $routes->get('(:any)', 'Pages::view/$1');

Now point your browser to your local development environment where youinstalled CodeIgniter and add /news/create to the URL.Add some news and check out the different pages you made.../_images/tutorial3.png../_images/tutorial4.png../_images/tutorial9.png

Congratulations

You just completed your first CodeIgniter4 application!

The image to the left shows your project’s app folder,with all of the files that you created in green.The two modified configuration files (Database & Routes) are not shown.