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.
Related
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(); ?>
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();
How can I add a Glyphicons Icons in the input below?
A part of the code:
class GrupoUsuarioForm{
$this->setAttributes(array(
'method' => 'POST',
'class' => 'formGrupoUsuario',
'name' => 'formGrupoUsuario'
));
$this->setInputFilter(new GrupoUsuarioInputFilter());
$dataCadastro = new Text('data_grp');
$dataCadastro->setValue(date('d/m/Y'))
->setAttributes(array(
//'style' => 'width: 20%',
'id', 'dataGrp',
'readOnly' => 'true'
));
$dataCadastro->setLabel('Data do Cadastro');
$this->add($dataCadastro);
Would like this return HTML
<label>Textbox with calendar icon</label>
<div class="input-append"><input type="text" id="" name="">
<span class="add-on"><i class="icon-calendar"></i></span></div>
Where excatly do you want put this icon?
You can render form's elements as you want.
In controller:
public function myAction()
{
return new ViewModel([
'form' => new GrupoUsuarioForm()
]);
}
In your view:
// HTML code here
...
<?php $form = $this->form; ?>
<?php $form->prepare(); ?>
<?php echo $this->form()->openTag($form); ?>
...
<?php echo $this->formLabel($form->get('data_grp')); ?>
<div class="input-group">
<div class="input-append">
<?php echo $this->formInput($form->get('data_grp')); ?>
<span class="add-on"><i class="icon-calendar"></i></span>
</div>
</div>
...
<?php echo $this->form()->closeTag(); ?>
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; ?>
Not work my ajax validation in Yii. Why?
public function actionRegister()
{
$model = new Users;
$model->scenario = 'register';
$this->performAjaxValidation($model);
if(isset($_POST['Users']))
{
$model->attributes=$_POST['Users'];
$model->date = time();
$model->count_login = 0;
$model->count_orders = 0;
$model->total_price = 0;
$model->count_items = 0;
if($model->save())
{
Yii::app()->user->setFlash('success', 'Вы успешно зарегистрировались! Подтвердите свой электронный адрес, вам было выслано письмо!');
}else{
Yii::app()->user->setFlash('error', 'Ошибка регистрации!');
}
}
$this->render('register',array(
'model' => $model,
));
}
<?php
/* #var $this SiteController */
/* #var $model Users */
/* #var $form CActiveForm */
?>
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'users-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'action' => Yii::app()->createUrl('site/register'),
'enableAjaxValidation'=>true,
'enableClientValidation' => true,
'clientOptions' => array(
//'validationUrl' => Yii::app()->createUrl('site/register'),
'validateOnSubmit' => true,
'validateOnChange' => true,
'validateOnType' => true
)
)); ?>
<style>
label{
width: 100%;
}
</style>
<div class="jumbotron">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><strong>Регистрация</strong></h3>
</div>
<div class="panel-body">
<div class="alert alert-info">
<strong>Важно!</strong> Следующие поля обязательны к заполнению. Они помогут нам успешно доставить к вам товар!
<p>
<?php echo $form->errorSummary($model); ?>
</p>
</div>
<fieldset>
<label>
<div class="col-md-3">
<?php echo $form->labelEx($model,'name'); ?>
</div>
<div class="col-md-3">
<?php echo $form->textField($model, 'name', array('size'=>50, 'maxlength'=>50, 'class'=>'form-control')); ?> <?php echo $form->error($model,'name'); ?>
</div>
</label>
</fieldset>
Thanks!
I am included JQuery twice. Need once and with framework.
<?php Yii::app()->getClientScript()->registerCoreScript('jquery'); ?>