En este capítulo continuamos con la acción-vista "View" en la cual estamos listando los registros de la tabla alumnos, le integraremos un formulario de búsqueda y así poder filtrar y mostrar los resultados según el criterio de búsqueda del usuario, para ello generaremos la consulta a través del método findBySql($sql) de la clase ActiveRecord.
El código que interviene en este capítulo lo podéis ver a continuación:
Vista view.php
<?php
use yii\helpers\Url;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<a href="<?= Url::toRoute("site/create") ?>">Crear un nuevo alumno</a>
<?php $f = ActiveForm::begin([
"method" => "get",
"action" => Url::toRoute("site/view"),
"enableClientValidation" => true,
]);
?>
<div class="form-group">
<?= $f->field($form, "q")->input("search") ?>
</div>
<?= Html::submitButton("Buscar", ["class" => "btn btn-primary"]) ?>
<?php $f->end() ?>
<h3><?= $search ?></h3>
<h3>Lista de alumnos</h3>
<table class="table table-bordered">
<tr>
<th>Id Alumno</th>
<th>Nombre</th>
<th>Apellidos</th>
<th>Clase</th>
<th>Nota Final</th>
<th></th>
<th></th>
</tr>
<?php foreach($model as $row): ?>
<tr>
<td><?= $row->id_alumno ?></td>
<td><?= $row->nombre ?></td>
<td><?= $row->apellidos ?></td>
<td><?= $row->clase ?></td>
<td><?= $row->nota_final ?></td>
<td><a href="#">Editar</a></td>
<td><a href="#">Eliminar</a></td>
</tr>
<?php endforeach ?>
</table>
Modelo de validación para el formulario de búsqueda FormSearch.php
<?php
namespace app\models;
use Yii;
use yii\base\model;
class FormSearch extends model{
public $q;
public function rules()
{
return [
["q", "match", "pattern" => "/^[0-9a-záéíóúñ\s]+$/i", "message" => "Sólo se aceptan letras y números"]
];
}
public function attributeLabels()
{
return [
'q' => "Buscar:",
];
}
}
La acción View que se encuentra en el controlador SiteController.php
<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
use app\models\ValidarFormulario;
use app\models\ValidarFormularioAjax;
use yii\widgets\ActiveForm;
use yii\web\Response;
use app\models\FormAlumnos;
use app\models\Alumnos;
use app\models\FormSearch;
use yii\helpers\Html;
class SiteController extends Controller
{
public function actionView()
{
$table = new Alumnos;
$model = $table->find()->all();
$form = new FormSearch;
$search = null;
if($form->load(Yii::$app->request->get()))
{
if ($form->validate())
{
$search = Html::encode($form->q);
$query = "SELECT * FROM alumnos WHERE id_alumno LIKE '%$search%' OR ";
$query .= "nombre LIKE '%$search%' OR apellidos LIKE '%$search%'";
$model = $table->findBySql($query)->all();
}
else
{
$form->getErrors();
}
}
return $this->render("view", ["model" => $model, "form" => $form, "search" => $search]);
}
public function actionCreate()
{
$model = new FormAlumnos;
$msg = null;
if($model->load(Yii::$app->request->post()))
{
if($model->validate())
{
$table = new Alumnos;
$table->nombre = $model->nombre;
$table->apellidos = $model->apellidos;
$table->clase = $model->clase;
$table->nota_final = $model->nota_final;
if ($table->insert())
{
$msg = "Enhorabuena registro guardado correctamente";
$model->nombre = null;
$model->apellidos = null;
$model->clase = null;
$model->nota_final = null;
}
else
{
$msg = "Ha ocurrido un error al insertar el registro";
}
}
else
{
$model->getErrors();
}
}
return $this->render("create", ['model' => $model, 'msg' => $msg]);
}
public function actionSaluda($get = "Tutorial Yii")
{
$mensaje = "Hola Mundo";
$numeros = [0, 1, 2, 3, 4, 5];
return $this->render("saluda",
[
"saluda" => $mensaje,
"numeros" => $numeros,
"get" => $get,
]);
}
public function actionFormulario($mensaje = null)
{
return $this->render("formulario", ["mensaje" => $mensaje]);
}
public function actionRequest()
{
$mensaje = null;
if (isset($_REQUEST["nombre"]))
{
$mensaje = "Bien, has enviando tu nombre correctamente: " . $_REQUEST["nombre"];
}
$this->redirect(["site/formulario", "mensaje" => $mensaje]);
}
public function actionValidarformulario()
{
$model = new ValidarFormulario;
if ($model->load(Yii::$app->request->post()))
{
if($model->validate())
{
//Por ejemplo, consultar en una base de datos
}
else
{
$model->getErrors();
}
}
return $this->render("validarformulario", ["model" => $model]);
}
public function actionValidarformularioajax()
{
$model = new ValidarFormularioAjax;
$msg = null;
if ($model->load(Yii::$app->request->post()) && Yii::$app->request->isAjax)
{
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if ($model->load(Yii::$app->request->post()))
{
if ($model->validate())
{
//Por ejemplo hacer una consulta a una base de datos
$msg = "Enhorabuena formulario enviado correctamente";
$model->nombre = null;
$model->email = null;
}
else
{
$model->getErrors();
}
}
return $this->render("validarformularioajax", ['model' => $model, 'msg' => $msg]);
}
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionIndex()
{
return $this->render('index');
}
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
public function actionAbout()
{
return $this->render('about');
}
}
Ver el vídeo tutorial de Yii Framework 2 en Youtube
No hay comentarios:
Publicar un comentario