ActiveForm is not loaded - php

I'm trying to learn working with yii2, made a Controller, a Model and a View in backend and I used ActiveForm but it ends up showing me what I have written in the view instead of loading the form meaning instead of making a form this is what displays:
field($model,'UserName'); ?> field($model,'Password'); ?> 'btn btn-primary']); ?>
these are my codes
controller:
<?php
namespace backend\controllers;
use yii\web\Controller;
use Yii;
class UserController extends Controller
{
public function actionIndex()
{
return $this->render('index');
}
public function actionNew()
{
$model = new UserForm;
if($model->load(Yii::$app->request->post()) && $model->validate())
{
return $this->render('_show',['model'=>$model]);
}
else
{
return $this->render('_form',['model'=>$model]);
}
}
}
?>
View:
<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
?>
<?php $form=ActiveForm::begin(); ?>
<? $form->field($model,'UserName'); ?>
<? $form->field($model,'Password'); ?>
<? Html::submitButton('login', ['class'=> 'btn btn-primary']); ?>
<?php ActiveForm::end(); ?>
Model:
<?php
namespace backend\models;
use Yii;
use yii\base\Model;
class UserForm extends Model
{
public $UserName;
public $Password;
public function rules()
{
return
[
[['UserName','Password'],'required'],
['Password','Password']
];
}
}
?>
main.php
<?php
/* #var $this \yii\web\View */
/* #var $content string */
use backend\assets\AppAsset;
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use common\widgets\Alert;
AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?php $this->registerCsrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<div class="wrap">
<?php
NavBar::begin([
'brandLabel' => Yii::$app->name,
'brandUrl' => Yii::$app->homeUrl,
'options' => [
'class' => 'navbar-inverse navbar-fixed-top',
],
]);
$menuItems = [
['label' => 'Home', 'url' => ['/site/index']],
];
if (Yii::$app->user->isGuest) {
$menuItems[] = ['label' => 'Login', 'url' => ['/site/login']];
} else {
$menuItems[] = '<li>'
. Html::beginForm(['/site/logout'], 'post')
. Html::submitButton(
'Logout (' . Yii::$app->user->identity->username . ')',
['class' => 'btn btn-link logout']
)
. Html::endForm()
. '</li>';
}
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => $menuItems,
]);
NavBar::end();
?>
<div class="container">
<?= Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>
<?= Alert::widget() ?>
<?= $content ?>
</div>
</div>
<footer class="footer">
<div class="container">
<p class="pull-left">© <?= Html::encode(Yii::$app->name) ?> <?= date('Y') ?></p>
<p class="pull-right"><?= Yii::powered() ?></p>
</div>
</footer>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>

Just echo the form fields. Use <?= instead of <?
<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
?>
<?php $form=ActiveForm::begin(); ?>
<?= $form->field($model,'UserName'); ?>
<?= $form->field($model,'Password'); ?>
<?= Html::submitButton('login', ['class'=> 'btn btn-primary']); ?>
<?php ActiveForm::end(); ?>

Related

Yii2 - list every post - coding error

I am new in Yii2 and I made a site where i can write posts, view them, delete them etc...
I want to list every post from a DB on one page as a "timeline"
My code does not list any error simply just show the very first record only.
Here is my code from (views) index.php
<?php
use yii\helpers\Html;
use yii\widgets\ListView;
/* #var $this yii\web\View */
/* #var $searchModel frontend\models\search\TweetSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'My tweets';
?>
<div class="tweet-model-index">
<h1 class="text-center"><?= Html::encode($this->title) ?></h1>
<p class="text-center">
<?= Html::a('New Tweet', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php
$con = \Yii::$app->db;
$sql = $con->createCommand("SELECT * FROM tweet ORDER BY created_at DESC");
$tweets = $sql->queryAll();
if(!$tweets)
echo '<h2> This is empty </h2>';
else{
foreach($tweets as $tweet){
?>
<hr>
<div class="container-fluid">
<div class="col-md-8 col-md-offset-2">
<h2 class="text-left">
<?php echo $tweet['tweet_title']; ?>
<br><small>Author: <b><?php echo $tweet['author_id'];?> </b>Created at: <b><?php echo date(($tweet['created_at']));?></b>
<br>Updated at: <b><?php echo date(($tweet['updated_at']));?>
</small>
</h2>
<p class="text-left">
<?= Html::a('Update', ['update', 'id' => $tweet['tweet_id']], ['class' => 'btn btn-primary']) ?>
<?= Html::a('View', ['view', 'id' => $tweet['tweet_id']], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $tweet['tweet_id']], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
</div>
</div>
</div>
<?php endforeach; ?>
<?php endif; ?>
May i ask You guys, how can I count the views on each post?
I tried this on my TweetController but doesn't work.
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id));
}
Start using braces!
else
foreach($tweets as $tweet);
?>
to this:
else {
foreach($tweets as $tweet) {
?>
or even better in VIEWS:
else:
foreach($tweets as $tweet):
?>
.....
.....
<?php endforeach; ?>
<?php endif; ?>
update from
$tweets = $sql->query();
to
$tweets = $sql->queryAll();

Yii2: Why setFlash didn't work when render a page in Modules?

I've an application using Yii2, basic template. In my app, I'm using Yii::$app->session-setFlash for show a message when render a page.
When I place my application in app, it work well. But when I move the app into module, it didn't show a message. The module called school
This is the code I've using for showing message and render page in my app/module/school
Yii::$app->session->setFlash('error', "Error!");
return Yii::$app->response->redirect(['school/student/create']);
the page successfully return to school/student/create page, but didn't show the message.
and this the code when I place the app in app
Yii::$app->session->setFlash('error', "Error!");
return Yii::$app->response->redirect(['create']);
the code above successfully return to page student/create and show the message.
This is my app directory structure:
--school
--assets
--commands
--config
--controllers
--file
--mail
--models
--modules //this the module
--school
--controllers
--models
--search
--views
--Module.php
--runtime
--test
--vendor
--views
--web
.....
Anyone know why It happen? and How do I can solve this?
Anyhelp will be appreciated, thanks :)
Edited:
This is code:
app/modules/school/views/student/_form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\file\FileInput;
/* #var $this yii\web\View */
/* #var $model backend\models\Student */
/* #var $form yii\widgets\ActiveForm */
?>
<script type="text/javascript" src="../../web/js/jquery-1.5.2.min.js"> </script>
<div class="student-form">
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?=
$form->field($model, 'file')->widget(FileInput::classname(), [
'options' => [
'accept' => 'doc/*', 'file/*',
],
'pluginOptions' => [
'allowedFileExtensions' => ['csv', 'xls', 'xlsx'],
'showUpload' => FALSE,
'showPreview' => FALSE,
]
]);
?>
<?= Html::submitButton('<i class="glyphicon glyphicon-save-file"></i> UPLOAD', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary'], ['fakturout/create']) ?>
<?php ActiveForm::end(); ?>
</div>
and
app/modules/school/view/student/create.php
<?php
use yii\helpers\Html;
/* #var $this yii\web\View */
/* #var $model backend\models\Student */
$this->title = 'Student';
?>
<div class="title">
<?= Html::encode($this->title) ?>
</div>
<?=
$this->render('_form', [
'model' => $model,
])
?>
You have no line of code to render your session flash messages in the module. To test it add following code in the app/modules/school/view/student/create.php:
<?php
use yii\helpers\Html;
/* #var $this yii\web\View */
/* #var $model backend\models\Student */
$this->title = 'Student';
?>
<?php if (Yii::$app->session->hasFlash('success')): ?>
<div class="alert alert-success">
<?= Yii::$app->session->getFlash('success'); ?>
</div>
<?php endif; ?>
<?php if (Yii::$app->session->hasFlash('warning')): ?>
<div class="alert alert-warning">
<?= Yii::$app->session->getFlash('warning'); ?>
</div>
<?php endif; ?>
<?php if (Yii::$app->session->hasFlash('error')): ?>
<div class="alert alert-danger">
<?= Yii::$app->session->getFlash('error'); ?>
</div>
<?php endif; ?>
<div class="title">
<?= Html::encode($this->title) ?>
</div>
<?=
$this->render('_form', [
'model' => $model,
])
?>
I recommend add following code at the widget and render widget in your layout template (app/views/layouts/main.php), or add in layout template without widget:
<?php if (Yii::$app->session->hasFlash('success')): ?>
<div class="alert alert-success">
<?= Yii::$app->session->getFlash('success'); ?>
</div>
<?php endif; ?>
<?php if (Yii::$app->session->hasFlash('warning')): ?>
<div class="alert alert-warning">
<?= Yii::$app->session->getFlash('warning'); ?>
</div>
<?php endif; ?>
<?php if (Yii::$app->session->hasFlash('error')): ?>
<div class="alert alert-danger">
<?= Yii::$app->session->getFlash('error'); ?>
</div>
<?php endif; ?>

How can I add a for each inside of another for each in Yii2?

Well what I want to do is in the first for each -which is done- to retrieve data from the model preguntas and with previous information I want to generate for each data a radiolist.
In case you don't understand, what I'm trying to do is
For each Questions(Preguntas) found in model Preguntas generate a HTML label, and for each label done generate a radiolist with five buttons.
?php use yii\helpers\Html;
use yii\widgets\ActiveForm;
use unclead\multipleinput\MultipleInput;
use app\models\Preguntas;
use yii\db\ActiveRecord;
use yii\widgets\DetailView;
use yii\db\Query;
use app\models\Respuestas;
/* #var $this yii\web\View */
/* #var $model app\models\Encuestas */
/* #var $form yii\widgets\ActiveForm */
?> <div class="encuestas-form"> <?php $form=ActiveForm::begin();
?> <?=$form->field($model, 'titulo')->textInput(['maxlength'=> true]) ?> <?=$form->field($model, 'objetivo')->textInput(['maxlength'=> true]) ?> <?php $respuestas=Respuestas::find()->all();
?> <?php foreach (Preguntas::find()->all() as $pregunta) {
$data=$pregunta->preguntas;
echo "<br>";
echo Html: : label( $data, 'Pregunta', ['class'=> 'control-label', 'style'=> 'color:black']);
echo "<br>";
foreach ((array)$data as $respuesta) {
echo Html: : radio('agree', true, ['label'=> 'I agree', 'value'=> '1']);
;
echo Html: : radio('agree', true, ['label'=> 'I agree', 'value'=> '2']);
;
}
}
?> <div class="form-group"> <?=Html::submitButton( $model->isNewRecord ? 'Create': 'Update', ['class'=> $model->isNewRecord ? 'btn btn-success': 'btn btn-primary'])?> </div> <?php ActiveForm::end();
?> </div>
Thanks

How to fix the "Undefined variable" error in Yii2 view?

Here is my controller:
class RoomController extends Controller
{
public function actionCreate()
{
$model = new Room();
$modelSave = false;
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
}
return $this->render('create', ['model' => $model,'modelSaved' => $modelSave]);
}
}
and here is my view
<?php if($modelSave) { ?>
<div class = "alert alert-success" >
Model ready to be saved!
</div>
<?php } ?>
<?php $form = ActiveForm::begin(); ?>
<div class="row">
<div class = "col-lg-12">
<h1>Room Form</h1>
<?= $form->field($model,'floor')->textinput()?>
<?= $form->field($model,'room_number')->textinput() ?>
<?= $form->field($model,'has_conditioner')->checkbox() ?>
<?= $form->field($model,'has_tv')->checkbox() ?>
<?= $form->field($model,'has_phone')->checkbox() ?>
<?= $form->field($model,'available_form')->textinput() ?>
<?= $form->field($model,'price_per_day')->textinput() ?>
<?= $form->field($model,'description')->textarea() ?>
</div>
</div>
<div class="form-group">
<?= Html::submitButton('create',['class'=>'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
when i checked whether if it working,
the ErrorException shows:
PHP Notice – yii\base\ErrorException
Undefined variable: modelSave
I've tried to debug, but I have no idea why the $modelSave can't send to the view "create".
You test
<?php if($modelSave) { ?>
but in your render you have
return $this->render('create', ['model' => $model,'modelSaved' => $modelSave]);
use
<?php if($modelSaved) { ?>
You don't call the variable by its name, you should try to check $modelSaved since this is the name you give it
replace
<?php if($modelSave) { ?>
by
<?php if($modelSaved) { ?>

Yii2 Executes the view twice

I've changed the index action for the login action and now the view executes twice like this
Why this happend ?
Can anyone help me ?
This is the layout:
<?php
/* #var $this \yii\web\View */
/* #var $content string */
use yii\helpers\Html;
use app\assets\LoginAsset;
LoginAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
</head>
<body class="fixed-header">
<?php $this->beginBody() ?>
<div class="login-wrapper">
<?= $content ?>
</div>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
This is the view:
<?php
/* #var $this yii\web\View */
/* #var $form yii\bootstrap\ActiveForm */
/* #var $model app\models\LoginForm */
use yii\bootstrap\ActiveForm;
use yii\helpers\Url;
use yii\helpers\Html;
$this->title = 'Tramite al dia - Login';
?>
<div class="bg-pic">
<!-- START Background Pic
<img src="<?= Url::base() ?>/public/pages/assets/img/demo/new-york-city-buildings-sunrise-morning-hd-wallpaper.jpg" height="1200" width="1920" class="lazy"> -->
<!-- END Background Pic -->
<!-- START Background Caption-->
<div class="bg-caption pull-bottom sm-pull-bottom text-white p-l-20 m-b-20">
<h2 class="semi-bold text-white">
En la facilidad esta la felicidad de las personas.
</h2>
<p class="small">
Te facilitamos el control del día a día con el tramite y gestión de sus documentos, <br> Tramite al día © 2015
</p>
</div>
<!-- END Background Caption-->
</div>
<div class="login-container bg-white">
<div class="p-l-50 m-l-20 p-r-50 m-r-20 p-t-50 m-t-30 sm-p-l-15 sm-p-r-15 sm-p-t-40">
<!-- <img src="<?= Url::base() ?>/public/pages/assets/img/logo.png" alt="logo" width="78" height="22"> -->
<p class="p-t-35">Accede a tu cuenta</p>
<!-- START Login Form -->
<?php $form = ActiveForm::begin(); ?>
<!-- START Form Control-->
<div class="form-group form-group-default">
<label>Usuario</label>
<div class="controls">
<?= $form->field($model, "usuario")->label(FALSE); ?>
</div>
</div>
<!-- END Form Control-->
<!-- START Form Control-->
<div class="form-group form-group-default">
<label>Contraseña</label>
<div class="controls">
<?= $form->field($model, "clave")->passwordInput()->label(FALSE); ?>
</div>
</div>
<!-- START Form Control-->
<div class="row">
<div class="col-md-6 no-padding">
<?= $form->field($model, "recuerdaMe")->checkbox()->label(FALSE) ?>
<label>Mantener sesión iniciada</label>
</div>
<div class="col-md-6 text-right m-t-10">
Necesita ayuda?
</div>
</div>
<!-- END Form Control-->
<?= Html::submitButton("Entrar", ["class" => "btn btn-primary btn-cons m-t-10"]) ?>
<?php ActiveForm::end(); ?>
<!--END Login Form-->
</div>
</div>
And this is the controller
<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
class SiteController extends Controller {
public $layout = "login";
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() {
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()):
return $this->redirect(["landing/index"]);
else:
return $this->render('index', [
'model' => $model,
]);
endif;
}
public function actionLogout() {
Yii::$app->user->logout();
return $this->goHome();
}
}
First time this happend to me.
I am pretty sure it's about the rendering in your layout files. Show the code of your views/layouts/main.php and if you have sub-templates those as well. E.g. if you have there multiple parts of the following code you will get the result you mentioned, e.g. multiple echo of $content.
<?php $this->beginBody() ?>
<?= $content ?>
<?php $this->endBody() ?>
Another possibility could be multiple call of echo $this->render('yourview',...) in your controller code. You should always return and not echo those render calls e.g. return $this->render('yourview',...) instead. Then is couldn't be rendered multiple times.

Categories