• No results found

Example – creating and updating a room from a form

In document Yii2 By Example - Sample Chapter (Page 45-51)

Just from following the instructions in the previous paragraph, we will try to create and update a room from the HTML form.

We now update the previously created actionCreate() method in RoomsController with some code to instantiate a new model object, check the content of the $_POST array, and if it is set, we call save() on the model:

public function actionCreate() {

// 1. Create a new Room instance;

$model = new Room();

// 2. Check if $_POST['Room'] contains data;

if(isset($_POST['Room'])) {

$model->attributes = $_POST['Room'];

// Save model if($model->save()) {

// If save() success, redirect user to action view.

return $this->redirect(['view', 'id' => $model->id]);

} }

return $this->render('create', ['model' => $model]);

}

To update the view in basic/views/rooms/create.php, pass:

<?php

use yii\widgets\ActiveForm;

use yii\helpers\Html;

?>

<div class="row">

<div class="col-lg-6">

<h2>Create a new room</h2>

<?php $form = ActiveForm::begin(['id' => 'room-form']) ?>

<?php echo $form->field($model, 'floor')->textInput(); ?>

<?php echo $form->field($model, >textInput(); ?>

<?php echo $form->field($model, >checkbox(); ?>

<?php echo $form->field($model, 'has_tv')->checkbox(); ?>

<?php echo $form->field($model, 'has_phone')->checkbox();

?>

<?php echo $form->field($model, >textInput(); ?>

<?php echo $form->field($model, >textInput(); ?>

<?php echo $form->field($model, >textArea(); ?>

<?php echo Html::submitButton('Save', ['class' => 'btn btn-primary']); ?>

<?php ActiveForm::end() ?>

</div>

</div>

By default, ActiveForm::begin() creates a form that has client validation enabled;

therefore, the form will be submitted only when all the validation rules are satisfi ed as the submit button is rendered using yii\helpers\Html.

Pay attention to the top of view that contains the use keyword to defi ne the complete path of the classes Html and ActiveForm:

use yii\widgets\ActiveForm;

use yii\helpers\Html;

Point your browser to http://hostname/basic/rooms/create to display the form to create a new room. The following screenshot shows what you should display, reporting in it some particular conditions:

The form to create a new room

This screenshot presents different states of fi elds: the fl oor input has a red border because it has the wrong type of content (it must be an integer!), the room number has a green border to indicate that is correct, and the Available From fi eld has a red border because it is required but the user left it blank. The framework provides a more concise form to fi ll in attributes if $_POST data is available:

$model->load(Yii::$app->request->post());

This fi lls in the attributes of the model if the $_POST[model-class] content is available, and with this suggestion we can change the actionCreate content as follows:

public function actionCreate() {

if( $model->load(Yii::$app->request->post()) && >save()) )

This is extraordinarily concise! Similarly, we can handle the update action to save changes to an existing model.

We can make a reusable form by putting its content in an external. Create a new fi le in basic/views/rooms/_form.php (the fi rst underscore indicates that this is a view that is includable in other views) and cut and paste the code about form generation from the create view to this new _form view:

<?php

use yii\widgets\ActiveForm;

use yii\helpers\Html;

?>

<?php $form = ActiveForm::begin(['id' => 'room-form']) ?>

<?php echo $form->field($model, 'floor')->textInput(); ?>

<?php echo Html::submitButton('Create', ['class' => 'btn btn-primary']); ?>

<?php ActiveForm::end() ?>

In the basic/views/rooms/create.php fi le, instead of the form code, just put the code to render the _form view in it:

<?php echo $this->render('_form', ['model' => $model]); ?>

When we modify the create view, remember to pass $model as the second parameter to render the _form view.

We are ready to build the update fl ow in order to update the room content from a form. Firstly, create an action in basic/controllers/RoomsController.php named actionUpdate, passing $id as a parameter that identifi es the primary key to fi nd the model.

In this action, we will put some code to get the model based on the id primary key, check whether the $_POST array contains data, and then save the model:

public function actionUpdate($id) {

// 1. Create a new Room instance;

$model = Room::findOne($id);

// 2. Check if $_POST['Room'] contains data and save model;

if( ($model!=null) && >post()) && ($model->save()) )

{

return $this->redirect(['detail', 'id' => >id]);

}

return $this->render('update', ['model' => $model]);

}

This is basically equivalent to the code for the create action. Now, create the update view in basic/views/rooms/update.php with the following content:

<div class="row">

<div class="col-lg-6">

<h2>Update a room</h2>

<?php echo $this->render('_form', ['model' => $model]); ?>

</div>

</div>

From the database, check for one existing room and type the id value of this URL in your browser: http://hostname/basic/rooms/update?id=id-found.

For example, if id of an existing room is 1, type this URL in your browser:

http://hostname/basic/rooms/update?id=1

This will show a form with the fi lled in fi eld based on the model attributes' content.

This example is complete, having built the detail view, which shows the content of model attributes. Create an action named actionDetail, passing $id as a parameter, which identifi es the primary key to fi nd the model:

public function actionDetail($id) {

// 1. Create a new Room instance;

$model = Room::findOne($id);

return $this->render('detail', ['model' => $model]);

}

Then, create the detail view to display some of the model attributes' values in basic/views/rooms/detail.php:

<table class="table">

<tr>

<th>ID</th>

<td><?php echo $model['id'] ?></td>

</tr>

<tr>

<th>Floor</th>

<td><?php echo $model['floor'] ?></td>

</tr>

<tr>

<th>Room number</th>

<td><?php echo $model['room_number'] ?></td>

</tr>

</table>

Now after successfully creating or updating model, the detail view will be displayed with the content of some attributes of the model.

In document Yii2 By Example - Sample Chapter (Page 45-51)

Related documents