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();
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'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; ?>
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
I would like to this, but with yii framework:
<span class="btn default btn-file">
<span class="fileinput-new">Select image</span>
<span class="fileinput-exists">Change</span>
<input type="file" name="..."></input>
</span>
trying to do this way but doesn't work;
echo Button::widget([
'label' => 'Select Image',
'options' => ['class' => 'btn default btn-file'],
'options' => ['class' => 'fileinput-new'],
]);
I'm very newbie in yii framework and I've been spending some time trying to do this but without success. Anyhelp would be very apreciated
The make this input, cou can use either an ActiveForm (if you have a model) like this:
<?php
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'attribute')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton('Submit') ?>
</div>
<?php ActiveForm::end() ?>
Or the Html helper (if you don't want a model):
<?php
use yii\helpers\Html;
?>
<?php $form = Html::beginForm(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= Html::fileInput('...') ?>
<div class="form-group">
<?= Html::submitButton('Submit') ?>
</div>
<?php Html::endForm() ?>
I believe you won't have problem adapting the style after reading the docs. Both have the label method that allows you to edit the label as you want. Let me know if i wasn't clear on something.
try this :
<?= Html::a('label', ['/controller/action'], ['class'=>'btn btn-primary']) ?>
hope it will works as you want
If you want to use file field in the yii2. Create a form and place your field in the form.
<?php
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($modelobj, 'fieldname')->fileInput() ?>
<?= Html::submitButton('Submit')?>
<?php ActiveForm::end() ?>
I have been developing an application in Yii framework. At this point, I fall in an issue that is, I have an Order form where I select a registrant (all registrants come from database) from a dropdown, an item (all product items come from database) from dropdown and a input textbox where I type the quantity. There is a "ajaxSubmitButton" button to send all these values to the controller "actionCart" using Ajax. After receiving all values in the controller, I want to put all values in session variable. When I add another new item, the session values are being replaced what I want to hold all newly added items into the session variable. In this circumstance, what should I do. Please help me. I am giving my code snippets below:
in form:
<div class="form">
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'order-form',
'enableAjaxValidation'=>false,
'htmlOptions'=>array('class'=>'form-horizontal' , 'enctype'=>'multipart/form-data', ),
)); ?>
<div class="alert alert-info" xmlns="http://www.w3.org/1999/html">
<p class="note">Fields with <strong><span class="required">*</span></strong> are required.</p>
</div>
<?php echo $form->errorSummary($model); ?>
<div class="form-group">
<?php echo $form->labelEx($model,'registration_id', array('class' => 'control-label col-lg-4')); ?>
<div class="col-lg-8">
<?php
$data = CHtml::listData(Registration::model()->findAll(),'id', 'name');
echo $form->dropDownList($model,'registration_id',$data,array('class' => 'form-control chzn-select','prompt'=>'Select a Registrant'));
?>
</div>
<?php echo $form->error($model,'registration_id'); ?>
</div>
<div class="form-group">
<?php echo $form->labelEx($model,'item', array('class' => 'control-label col-lg-4')); ?>
<div class="col-lg-8">
<?php
$data = CHtml::listData(Products::model()->findAll(),'id', 'name');
echo $form->dropDownList($model,'item',$data, array('class'=>'form-control chzn-select' , 'id'=>'item', 'prompt'=>'Select an Item')); ?>
<?php
?>
</div>
<?php echo $form->error($model,'item'); ?>
</div>
<div class="form-group">
<?php echo $form->labelEx($model,'quantity', array('class' => 'control-label col-lg-4')); ?>
<div class="col-lg-2">
<?php
echo $form->textField($model,'quantity',array('class' => 'form-control','size'=>60,'maxlength'=>11));
?>
</div>
<?php echo $form->error($model,'quantity'); ?>
</div>
<div class="form-group">
<div class="col-lg-8 pull-right">
<?php
echo CHtml::ajaxSubmitButton('Add to Cart',Yii::app()->createUrl('admin/order/cart'),
array(
'type'=>'POST',
'update'=>'#cartResult',
),
array('class'=>'btn btn-primary btn-sm',));
?>
</div>
</div>
<div class="form-group">
<div id="cartResult" class="col-lg-12">
</div>
</div>
<?php $this->endWidget(); ?>
</div>
In controller:
public function actionCart()
{
if(isset($_POST["Order"])){
$item = $_POST["Order"];
$registration_id = $item["registration_id"];
$productId = $item["item"];
$quantity = $item["quantity"];
$quantity = $item["quantity"]=='' ? 1 : $item["quantity"];
$productInfo = Products::model()->findByPk(array('id'=>$productId));
$totalPrice = $productInfo->price * $quantity;
$session = Yii::app()->session;
$session['cart'] = array("product_id" => "$productId" , "product_name" => "$productInfo->name", "quantity" => "$quantity","price" => "$productInfo->price");
}
}