Rendering two models in View yii2 - php

I am trying to render two models in the actionView method, but without result. Checked some answers on previous questions and it seems my method is OK, but still do not work.
This is what a made for method view:
public function actionView($id)
{
$postModel = Post::find()->where(['post_id' => $id])->one();
$currUser = BlogUser::find()->where(['id' => $postModel->user_id])->one();
return $this->render('view', [
'model' => $this->findModel($id),
'author' => $currUser
]);
}
and my view page:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* #var $this yii\web\View */
/* #var $model app\models\Post */
//$this->title = $model->title;
//$this->params['breadcrumbs'][] = ['label' => 'Posts', 'url' => ['index']];
//$this->params['breadcrumbs'][] = $this->title;
?>
<div class="post-view">
<div class="content">
<div class="row">
<div class="col-md-3">
<?= $model->content;
$author->username;
?>
</div>
</div>
</div>
</div>
It tells that the author variable is undefined but cannot realize why when i render it in the action. Will appreciate every advice! Thank you!

Try using:
<div class="post-view">
<div class="content">
<div class="row">
<div class="col-md-3">
<?= $model->content; ?>
<?= $author->username; ?>
</div>
</div>
</div>
</div>

Related

How can i translate dynamic seo_url in Laravel?

I have dynamic laravel route. But i cannot translate this route when i use getTranslatedAttribute in the blade. I guess i got error because of the dynamic route.
i got this error.
Call to a member function getTranslatedAttribute() on null (View:/home//public_html/resources/views///)
my route
Route::get('/en/solutions/{seo_url}', function ($seo_url) {
App::setLocale('en');
$themes = App\Theme::all();
$services = App\Service::all();
$referances = App\Referance::all();
$blogs = App\Blog::all();
$solutions = App\Solution::all();
$announcements = App\Announcement::all();
$news = App\News::all();
$subsolutions = App\Subsolution::all();
$solution_details = App\Solution::where('seo_url', $seo_url)->first();
$pages = TCG\Voyager\Models\Page::all();
return view('tema.parallax.en.solution_detail', compact('services','solution_details','themes','pages' , 'referances' , 'blogs' , 'solutions', 'subsolutions' , 'news', 'announcements') );
});
my blade
<div class="container ms-content">
<div class="row justify-content-between">
<div class="row blog-sidebar grid-content col-lg-12">
<div class="grid-sizer col-12"></div>
#if ("en/solutions/" . $solution_details->getTranslatedAttribute('seo_url', 'en', 'fallbackLocale') == Request::path())
<article class="grid-item col-12 pb-lg-5">
<div class="work-card card--is-link"> <figure
class="card__img media-wrapper media-wrapper--21:9"><img
src="/public/storage/{{$solution_details->resim}}"
alt="{!!$solution_details->getTranslatedAttribute('baslik', 'en', 'fallbackLocale')!!}">
<div class="glow-wrap"><i class="glow"></i></div>
</figure>
<br>
<div class="card__content"><a class="card__title">
<h4>{!!$solution_details->getTranslatedAttribute('baslik', 'en', 'fallbackLocale')!!}
</h4>
</a>
<p class="text-sm post-excerpt">{!!$solution_details->getTranslatedAttribute('aciklama',
'en', 'fallbackLocale')!!}</p>
<div class="post-info__footer"><span class="post-info__divider"></span></div>
</div>
</div>
</article>
#endif
</div>
</div>
</div>
my Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use TCG\Voyager\Traits\Translatable;
class Solution extends Model
{
use Translatable;
protected $translatable = ['baslik', 'aciklama', 'aciklama_kisa', 'seo_url' , 'seo_baslik' ,'seo_aciklama'];
}
In short, I want to translate my dynamic url.
How can i do that ?

I want to update form with clone values in yii2

In update from, I am using values of two models with clone fields, in models variable, there are values but from not showing.
this error is showing
PHP Fatal Error – yii\base\ErrorException
Call to a member function isAttributeRequired() on array
my form code:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use frontend\models\PartyM;
use frontend\models\ProductM;
use frontend\models\Category;
/**
To add date picker and multiselection from dropdown list
Date: 03 April 2017
*/
use kartik\date\DatePicker;
use yii\helpers\Url;
/* #var $this yii\web\View */
/* #var $model frontend\models\SaleorderM */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="saleorder-m-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($modelm, 'ac_code')->dropDownList(ArrayHelper::map(PartyM::find()->where('type= :type', ['type' => 'S'])->all(),'ac_code','firmname'),['prompt'=>'Select Firmname'])->label("Firm Name");?>
<div id='main-product-section form-field' class='clonediv'>
<div class="product-section1 test1" id='1'>
<div class="product-area">
<?= $form->field($modeld, 'categoryid[]')->dropDownList(ArrayHelper::map(Category::find()->all(), 'categoryid', 'categoryname'),['prompt'=>'Select....'],['class' => 'your_class', 'id' => 'brandid1'])->label("Brand") ?>
</div>
<div class="code-area">
<?php
echo $form->field($modeld, 'productcode[]')->dropDownList(['prompt'=>'Select....'],['id'=>'brandid1-productcode'])->label("Product Code")?>
</div>
<div class="qty-area ">
<?= $form->field($modeld, 'qty[]')->textInput()->label("Quantity"); ?>
</div>
<div class="btn-area del">
</span>
</div>
</div>
</div>
<div class="form-group">
<div class="btn-area add">
<a href='javascript:void(0)' class='add_more' id='add_more' >Add More</a>
</div>
</div>
<?= $form->field($modeld, 'ordertype')->textInput()->label("Order Type"); ?>
<?php
// To add date picker
echo $form->field($modelm, 'orderdate')->widget(DatePicker::classname(), [
'name' => 'Saleorder Date',
'type' => DatePicker::TYPE_COMPONENT_APPEND,
'value' => date('Y-m-d'),
'pluginOptions' => [
'autoclose'=>true,
'format' => 'yyyy-mm-dd'
]
])->label("Saleorder Date"); ?>
<?= $form->field($modelm, 'courier')->textInput(['maxlength' => true])->label("Courier"); ?>
<?= $form->field($modelm, 'couriermode')->textInput(['maxlength' => true])->label("Courier Mode"); ?>
<?= $form->field($modelm, 'ordersource')->textInput(['maxlength' => true])->label("Order Source"); ?>
<?= $form->field($modelm, 'remarks')->textarea(array('rows'=>2,'cols'=>5)) ?>
<div class="form-group">
<?= Html::submitButton($modelm->isNewRecord ? 'Create' : 'Update', ['class' => $modelm->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>

Yii2 send id to hidden input via AJAX and reach it through POST

I want to send the data.user_id to hidden input with name user_id and after that take it through POST in the another html::a elem.
My view:
<?php
use yii\helpers\Html;
use yii\widgets\Pjax;
/* #var $this yii\web\View */
/* #var $searchModel app\models\PostSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
?>
<div class="post-index" style="position:relative;">
<div class="content">
<div class="row">
<div class="col-md-12 search-post">
<div class="col-md-4">
<?= Html::a('Create Post', ['create'], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Search', [''], ['class' => 'btn btn-default search-form']) ?>
<?= Html::radioList('search-type', 'search-type',
['item1' => 'by title', 'item2' => 'by tag'],
[
'style' => 'display: inline-block; margin-left: 10%'
]) ?>
</div>
<div class="col-md-8 search-input">
<?= Html::textInput('search-info', '',['class' => 'form-control']) ?>
</div>
<?php
$this->registerJs("
$('.search-form').on('click', function(event){
event.preventDefault();
var input = $('input[name=search-info]').val();
$.ajax({
type : 'GET',
url : '" . \yii\helpers\Url::to(['search-post']) . "?title='+input,
dataType : 'json',
success : function( data ){
$('#posts').css('display', 'none');
$('.none').fadeIn(1500);
$('.title-post h3').html( data.title );
$('.content-post').html( data.content );
$('input[name=user_id]').val( data.user_id);
}
});
});
");
?>
</div>
</div>
<div class="row">
<div class="none" style="display: none;">
<div class="title-post text-center"><h3></h3></div>
<div class="content-post"></div>
<div class="foot-post">
<form action="" method="post">
<?= Html::hiddenInput('user_id', '') ?>
</form>
<div class="text-left">
<?= Html::a('Go To Post', ['view', 'id' => $_POST['user_id']]) ?>
</div>
<div class="text-right">
<?= Html::a('Back','index', ['class' => 'btn btn-warning']) ?>
</div>
</div>
</div>
<?php Pjax::begin(['id' => 'posts']) ?>
<div class="col-md-12">
<?php
foreach ($posts as $post)
{
$id = $post->user_id;
$user = $userModel::find()->where(['id' => $id])->one();
echo "<div class='col-md-6 blog-post'>
<div class='col-md-3 post-prof-img'>"
. Html::img('../images/' . $user->image, ['alt' => 'image', 'class' => 'tall img-circle']) .
"<p class='text-center title-par'><strong><em> $user->username </em></strong></p>
<p class='text-center'> $post->date_create</p>
</div>
<div class='col-md-9 post-cont'><p>"
. Html::a('Click for more!',['view', 'id' => $post->post_id]) .
"</p><label class='text-center'> $post->title : </label>
<div class='fade-post'>
$post->content
</div>
</div>
</div>";
}
?>
</div>
<?php Pjax::end() ?>
</div>
</div>
</div>
As I can see it is not possible the way I am trying so please give some advice! Thank you in advance!
I think you got wrong idea about $_POST. The Undefined index: user_id is simply thrown because you have not submitted the form therefore $_POST['user_id'] does not exist.
You should change your code to use plain variable which will not be based on $_POST.
<?= Html::a('Go To Post', ['view', 'id' => $idThatIsNotPOST]) ?>
If you want to change the link using ajax you will have to alter its href. Something like: $("a").attr("href", "<replace current href id with ajax's>").

Saving data to db yii2

I'm trying to save data from my form to db. But when I click "submit" button nothing happened(page is refresh but my db table is blank) what I did wrong?
I'm create model which extend ActiveRecord:
class EntryForm extends \yii\db\ActiveRecord
{
public $id;
public $name;
public $email;
public $age;
public $height;
public $weight;
public $city;
public $checkboxList;
public $checkboxList1;
public $imageFiles;
public function rules()
{
return [
[['name', 'email','age','height','weight','city','checkboxList','checkboxList1'], 'required'],
[['imageFiles'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg','maxFiles' => 5],
['email', 'email'],
];
}
public static function tableName()
{
return 'form';
}
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'name',
'email' => 'e-mail',
'age' => 'age',
'height' => 'height',
'weight' => 'weight',
'city' => 'city',
'checkboxList' => 'technies',
'checkboxList1' => 'english_level',
'imageFiles[0]' => 'photo_1',
'imageFiles[1]' => 'photo_2',
'imageFiles[2]' => 'photo_3',
'imageFiles[3]' => 'photo_4',
'imageFiles[4]' => 'photo_5'
];
}
public function insertFormData()
{
$entryForm = new EntryForm();
$entryForm->name = $this->name;
$entryForm->email = $this->email;
$entryForm->age = $this->age;
$entryForm->height = $this->height;
$entryForm->weight = $this->weight;
$entryForm->city = $this->city;
$entryForm->checkboxList = $this->checkboxList;
$entryForm->checkboxList1 = $this->checkboxList1;
$entryForm->imageFiles = $this->imageFiles;
return $form->save();
}
public function contact($email)
{
if ($this->validate()) {
Yii::$app->mailer->compose()
->setTo($email)
->setFrom('prozrostl#gmail.com')
->setSubject('Email from test app')
->setTextBody($this->name + $this->age + $this->height + $this->width + $this->city + $this->checkboxList + $this->checkboxList1 + $this->imageFiles)
->send();
return true;
} else {
return false;
}
}
}
then I update my view file to show the form, view it's just easy few fields and upload files button(but all information doesn't save)
<?php $form = ActiveForm::begin([
'id' => 'my-form',
'options' => ['enctype' => 'multipart/form-data']
]); ?>
<div class="row">
<div class="col-lg-6">
<?= $form->field($entryForm, 'name')->textInput(['class'=>'name_class'])->input('name',['placeholder' => "Имя"])->label(false); ?>
</div>
<div class="col-lg-6">
<?= $form->field($entryForm, 'email')->textInput()->input('email',['placeholder' => "E-mail"])->label(false); ?>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<?= $form->field($entryForm, 'age')->textInput()->input('age',['placeholder' => "Возраст(полных лет)"])->label(false); ?>
</div>
<div class="col-lg-6">
<?= $form->field($entryForm, 'height')->textInput()->input('height',['placeholder' => "Рост"])->label(false); ?>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<?= $form->field($entryForm, 'weight')->textInput()->input('weight',['placeholder' => "Вес"])->label(false); ?>
</div>
<div class="col-lg-6">
<?= $form->field($entryForm, 'city')->textInput()->input('city',['placeholder' => "Город проживания"])->label(false); ?>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<p><img class="describe_images" src="computer.png"></img>Нужна ли техника в аренду</p>
</div>
<?= $form->field($entryForm, 'checkboxList')->checkboxList(['no'=>'Нет', 'yes_camera'=>'Да,только камера', 'yes_both'=>'да,компьютер и камера'])->label(false) ?>
</div>
<div class="row">
<div class="col-lg-3">
<p><img class="describe_images" src="English.png"></img>Знание английского</p>
</div>
<?= $form->field($entryForm, 'checkboxList1')->checkboxList(['starter'=>'Без знания', 'elementary'=>'Базовый', 'intermediate'=>'Средний','up-intermediate'=>'Высокий','advanced'=>'Превосходный'])->label(false) ?>
</div>
<div class="row">
<div class="col-lg-6">
<div class="col-lg-6">
<p class="add_photo"><img class="describe_images" src="photo.png"></img>Добавить фото(до 5 штук)</p>
</div>
<div class="col-lg-6">
<?= $form->field($entryForm, 'imageFiles[]')->fileInput(['multiple' => true, 'accept' => 'image/*','id'=>'gallery-photo-add'])->label(false) ?>
</div>
</div>
<div class="col-lg-6 pixels-line">
<div class="preview"></div>
</div>
</div>
<div class="form-group">
<?= Html::submitButton('Отправить', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end() ?>
and then I add that code to my controller. I created new action ActionForm and put into that code:
public function actionForm()
{
$entryForm = new EntryForm();
if ($entryForm->load(Yii::$app->request->post()) && $entryForm->insertFormData()) {
}
}
Why do you redeclare the variables in the database? you're basically telling yii to ignore the attributes on the table.
public $id;
public $name;
public $email;
public $age;
public $height;
public $weight;
public $city;
public $checkboxList;
public $checkboxList1;
public $imageFiles;
Remove the public declarations and see if it works.
Your code looks ok, so probably you have some validation errors.
In the insertFormData() method add the following to get the validation errors:
if (!$entryForm->validate()){
var_dump($entryForm->getErrors());
}
Later edit:
Your insertFormData method is basically useless because the $entryForm->load loads the data from POST.
The second problem is probably with the file upload. To get the uploaded files use UploadedFile::getInstance($model, 'imageFile'). More info here
I suggest you to create a crud using Gii (the crud generator) and then implement the file upload according to the documentation mentioned above. And in this case you will see the validation errors too.

Yii Framework - in a main view I can't add a CActiveForm because it needs a model, when I set the model nothing happens

I put this on my view, and I have to add the <?php $model = new Usuarios; ?> and it works but then actually does not send the info to the database.
I tried on another view (index view) and without this it works: <?php $model = new Usuarios; ?>.
<a class="list-group-item">
<form role="form">
<div class="form">
<?php $model = new Usuarios; ?>
<?php $form = $this->beginWidget('CActiveForm', array(
'id' => 'usuarios-form',
'action' => $this->createUrl("usuarios/create"),
'enableAjaxValidation' => false,
)); ?>
<?php echo $form->errorSummary($model); ?>
<div style="padding:1px;" class="input-group input-group-sm">
<span class="input-group-addon">
<span class="glyphicon glyphicon-user" style="color:white"></span>
</span>
<?php echo $form->textField($model, 'Nombre', array('maxlength' => 128, 'placeholder' => 'Nombre y Apellido')); ?>
<?php echo $form->error($model, 'Nombre'); ?>
</div>
<div class="row buttons" style="padding:4%; color:white ; font-size:1.5vmax; font-family: Signika; border-radius:30px">
<center>
<?php echo CHtml::submitButton($model->isNewRecord ? 'Enviar' : 'Save'); ?>
</center>
</div>
<?php $this->endWidget(); ?>
</div>
</form>
</a>
This is what your controller action should look like:
public function actionCreate() {
$model = new Usuarios;
if(isset($_POST['Usuarios'])) {
// Populate the model with values from form
// These attributes must be set to safe in the model rules() function
$model->attributes = $_POST['Usuarios'];
// ->save() will validate the model with the validation rules
// in the Usuarios.php model. If you do not want validation, use ->update()
if($model->save()) {
$this->redirect(array('view', 'id' => $model->primaryKey));
}
}
$this->render('create', array(
'model' => $model, // You pass the model to the view page
));
}
In your model, you need to update the rules() function to accept the fields for saving in the database:
public function rules() {
return array(
array('Nombre', 'safe'),
);
}

Categories