font awesome use in kartik activeform - yii2 - font-awesome

I have using kartik active form in my Yii2 development so i want to add icons into the form field. I was followed this LINK and tried below coding
//registered font awesome
rmrevin\yii\fontawesome\AssetBundle::register($this);
<?php $form = ActiveForm::begin();
<?= $form->field($model, 'Bags_count',[
'feedbackIcon' => [
'default' => 'sort-numeric-desc',
'success' => 'ok',
'error' => 'exclamation-sign',
]
])->textInput()->hint(' Example: 4'); ?>
<?php ActiveForm::end(); ?>
I have found this unwanted coding by using chrome inspect element feature. hope this will helpful for the answer.

You can change the widget function to use font-awesome-class
Kartik-v Active Form Widget
protected function renderFeedbackIcon()
{
if (!$this->_hasFeedback) {
return '';
}
$config = $this->feedbackIcon;
$type = ArrayHelper::getValue($config, 'type', 'icon');
$prefix = ArrayHelper::getValue($config, 'prefix', 'fa fa-');
$id = Html::getInputId($this->model, $this->attribute);
return $this->getFeedbackIcon($config, 'default', $type, $prefix, $id) .
$this->getFeedbackIcon($config, 'success', $type, $prefix, $id) .
$this->getFeedbackIcon($config, 'error', $type, $prefix, $id);
}

Related

Yii2 UploadedFile::getInstance() returns null

When my form is sent UploadedFile::getInstance($model, 'images') returns null. I also tried UploadedFile::getInstanceByName('images'). In the $_POST array the images key is empty e.g. 'images' => ['']. The file exists in $_FILES array.
My code is pretty simple. My view:
<?php $form = ActiveForm::begin([
'options' => [
'class' => 'validation-wizard wizard-circle floating-labels',
'enctype'=>'multipart/form-data'
],
]); ?>
<?= $form->field($model, 'images[]')->fileInput([
'id' => 'image_0',
'class' => 'dropify',
'data-default-file' => ''
]) ?>
<?php ActiveForm::end() ?>
In my model I have:
public $images;
public function rules()
{
return [
['images', 'each', 'rule' => ['file']],
];
}
If you want to access an array of files, you need to use UploadedFile::getInstances() instead of UploadedFile::getInstance().
$files = UploadedFile::getInstances($model, 'images');
Good example of handling multiple files can be found in guide in Uploading Multiple Files section.

Yii2 Basic sql query in view

I'm trying to get the user profile image of the author of the content inside the view , my view is channel I created but I get this error on my view
Undefined variable: queryAvatar
on my view I did
//Yii2 View code
use yii\helpers\Html;
use yii\widgets\DetailView;
/* #var $this yii\web\View */
/* #var $model app\models\Channel */
$this->title = $model->Channel_name;
?>
<div class="channel-view">
<h1><?= Html::encode($this->title) ?></h1>
<div><?php echo $queryAvatar; ?></div> // THE LINE I ADD
<?php if($model->uid == Yii::$app->user->id):?>
<p>
<?= Html::a('Update', ['update', 'id' => $model->Channel_id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->Channel_id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?php endif;?>
</div>
and on my controller I created this function
//function on my controller
public function actionChannel($id)
{
$cchannel = new Channel();
$queryAvatar = (new \yii\db\Query())
->select(['uavatar'])
->from('userlogin')
->where(['uid' => $cchannel->uid])
->All();
return $this->render('channel', [
'model' => $this->findModel($id),
'queryAvatar '=> $queryAvatar ,
]);
}
in your controller you define an empty model so your $cchannel->uid is empty.
You must define first your model like this
public function actionChannel($id)
{
$cchannel = $this->findModel($id);
$queryAvatar = (new \yii\db\Query())
->select(['uavatar'])
->from('userlogin')
->where(['uid' => $cchannel->uid])
->All();
return $this->render('channel', [
'model' => $cchannel ,
'queryAvatar '=> $queryAvatar ,
]);
}
The problem can be caused by space when you created array of variable before giving to view.
return $this->render('channel', [
'model' => $this->findModel($id),
'queryAvatar '=> $queryAvatar ,
]);
remove space from 'queryAvatar '
Like this:
return $this->render('channel', [
'model' => $this->findModel($id),
'queryAvatar'=> $queryAvatar ,
]);
Another problem can be caused by partial view in side view. For example when you call view:channel from controller inside it may be you view called like this.
<?=$this->render('your_view')?>
So, you should pass your variable to this view also like this.
<?=$this->render('your_view',['queryAvatar'=>$queryAvatar])?>
And finally you cannot echo the varable $queryAvatar beacuse it is array of objects. Therefore use the function print_r();
Like this.
<div><?php print_r($queryAvatar); ?></div> // THE LINE I ADD

How to grab the value of a dropDownList in Yii2?

I am not grabbing the selected value ($model->attribute) on a dropDownList in Yii2, what could be wrong? Thanks
This is the code that is located on a View:
$command = $connection->createCommand('SELECT att1
FROM table
ORDER By table_id ASC');
$rows = $command->queryAll();
$command->execute();
$listData = ArrayHelper::index($rows, null, 'table_id');
Then on the same View I call to $listData
<div class="row">
<div class="col-lg-9">
<?php Pjax::begin(['enablePushState' => false]); ?>
<?php $form = ActiveForm::begin(['id' => 'test-form', 'options' => ['data-pjax' => true]
]); ?>
<?= $form->field($model, 'attribute')->dropDownList($listData, ['prompt'=>'List of attributes.']); ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'test-button']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php Pjax::end(); ?>
</div>
</div>
This is the Controller:
public function actionTest()
{
$model = new TestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->insertTest();
return $this->renderAjax('test', ['model' => $model]);
} else {
return $this->renderAjax('test', ['model' => $model]);
}
}
The Model has the definition of $attribute and insertTest() is a function that use the value of $attribute to query onto a DB.
Thinking of you should use
ArrayHelper::map($listData, 'table_id', 'table_id');
Because you need a one-dimensional array.
And it's better to use the ActiveRecord for queries to the database.
ArrayHelper Docs
You are selecting only att1 from table so you should map this column
$listData = ArrayHelper::index($rows, 'att1');
for debug try modify your actionTest commenting $model->insertTest(); and using $model->save();
if the value is saved in db then you should check inside you $model->insertTest() function
public function actionTest()
{
$model = new TestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
// $model->insertTest();
$model->save();
return $this->renderAjax('test', ['model' => $model]);
} else {
return $this->renderAjax('test', ['model' => $model]);
}
}
you should use map in ArrayHelper
$listdata = ArrayHelper::map(CategoryModel::find()->orderBy(['table_id' => SORT_ASC])->all(), 'table_id', 'table_text');
Note: 'table_text' is table attribute that will appear in dropdown label.
I found the solution to that issue.
By doing this way the form was not able to save the submitted information.
$command = $connection->createCommand('SELECT att1
FROM table
ORDER By table_id ASC');
$rows = $command->queryAll();
$command->execute();
$listData = ArrayHelper::index($rows, null, 'table_id');
However, by this way the form is able to grab the value selected and put it into the variable.
$rows = table::find()->all();
$listData = ArrayHelper::map($rows,'table_id','att1');

select2 and Pjax not work together in yii2

when i use pjax in yii2. selec2 widget stops working. while select2 working alone. (not working together)
im using select2 widgets and pjax together. but when submit form with pjax. in new form, select2 not work. (just show loading img). pls help me
what is problem?
I want to use both at the same time.
select2 extention page
in view:
<?php
use yii\helpers\Hrml;
use yii\widgets\Pjax;
/* #var $this yii\web\View */
/* #var $model app\models\Vitrin */
?>
<?php Pjax::begin(); ?>
<?php
if($model->getProductTypeSetting()=='both')
{
echo $this->render('_form', [
'model' => $model,
]);
}
?>
<?php Pjax::end(); ?>
in _form:
<!-- BEGIN PAGE CONTENT-->
<?= Html::beginForm(['vitrin/index', 'id' => $id], 'post'['data-pjax' => '']); ?>
<?= Html::activeInput('text', $model, 'name', ['class' => $username]) ?>
<?= Html::submitButton('Submit', ['class' => 'submit']) ?>
<?= Html::endForm() ?>
<!-- END PAGE CONTENT-->
in controller:
if(Yii::$app->request->post('productType'))
{
$model->productType = $_POST['productType'];
if($model->productType=='physical')
{
return $this->renderAjax('_formProduct', ['products' => $this->getProductName()]);
}
else
throw new \yii\web\HttpException(406, Yii::t('app', 'Your request is invalid.'));
}
in _formProduct:
<!-- BEGIN PAGE CONTENT-->
<?= Html::beginForm(['vitrin/index', 'id' => $id], 'post', ['data-pjax' => '']); ?>
<?php
echo Select2::widget([
'name' => 'name',
'data' => [1 => "First", 2 => "Second", 3 => "Third", 4 => "Fourth", 5 => "Fifth"],
'options' => [
'placeholder' => 'Select a type ...',
],
]);
?>
<?= Html::submitButton('Submit', ['class' => 'submit']) ?>
<?= Html::endForm() ?>
<!-- END PAGE CONTENT-->
and AppAssets class:
class AppAsset extends AssetBundle
{
public $basePath = '#webroot/themes/backend';
public $baseUrl = '#web/themes/backend/assets_t';
public $css = [
'bootstrap-rtl/css/bootstrap-rtl.min.css',
'bootstrap-rtl/css/bootstrap-responsive-rtl.min.css',
'font-awesome/css/font-awesome.css',
'fancybox/source/jquery.fancybox.css',
'uniform/css/uniform.default.css',
];
public $js = [
'bootstrap-rtl/js/bootstrap.min.js',
'js/jquery.blockui.js',
'uniform/jquery.uniform.min.js',
];
when submit _form with pjax. in _formProduct, select2 not work. (just show loading img).
Generally, when I use Pjax, other Js codes are deactivated.
In your view header:
use kartik\select2\Select2Asset;
Select2Asset::register($this);
Also make sure you have the latest Select2 widget.

dependent dropdown yii2. How to do?

can I create a dependent dropdown in yii2?
I have two tables:
'id','name_country"
'id','name_city','country_id'
and have two methods in my model:
public function getCountryList()
{
$models = NetCountry::find()->asArray()->all();
return ArrayHelper::map($models, 'id', 'country_name');
}
and
public function getCityList($parent_id) {
$models = \common\models\City::find()->where(['parent_id' => $country_id])->asArray()->all();
return ArrayHelper::map($models, 'id', 'name_city','country_id');
}
I have the first field:
<?= $form->field($model, 'country')->dropDownList($model->countryList),['id'=>'parent_id'];
and the second
<?= $form->field($model, 'city')->dropDownList($model->cityList);
I need to 'transmit' parent_id to controller and return city_list by AJAX (with JSON).
How can I do this? I saw an example in Yii1, but what about Yii2?
use the krajee extension for dependent drop down
Details is here Krejee dependent dropdown for yii2
or follow following instructions:
Install the extension via composer:
$ php composer.phar require kartik-v/dependent-dropdown "dev-master"
In your view :
use kartik\widgets\DepDrop;
// Normal parent select
echo $form->field($model, 'cat')->dropDownList($catList, ['id' => 'cat-id']);
// Dependent Dropdown
echo $form->field($model, 'subcat')->widget(DepDrop::classname(), [
'options' => ['id' => 'subcat-id'],
'pluginOptions' => [
'depends' => ['cat-id'],
'placeholder' => 'Select...',
'url' => Url::to(['/site/subcat'])
]
]);
// THE CONTROLLER
public function actionSubcat() {
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$cat_id = $parents[0];
$out = self::getSubCatList($cat_id);
// the getSubCatList function will query the database based on the
// cat_id and return an array like below:
// [
// ['id'=>'<sub-cat-id-1>', 'name'=>'<sub-cat-name1>'],
// ['id'=>'<sub-cat_id_2>', 'name'=>'<sub-cat-name2>']
// ]
echo Json::encode(['output'=>$out, 'selected'=>'']);
return;
}
}
echo Json::encode(['output'=>'', 'selected'=>'']);
}
creating dependent dropdown in yii2 without using any third party libraries is
quite as simple as yii1. you have to try following code written below as per your requirements.
use gii to create models,views, controller for respective tables.
suppose there r two table like country, city as u written.
then write the following code into views file for one controller(like country):
<?php
use yii\helpers\ArrayHelper;
use yii\widgets\ActiveForm;
?>
<div>
<?php
$dataCountry=ArrayHelper::map(\app\models\Country::find()->
asArray()->all(),'id', 'name');
$form = ActiveForm::begin();
echo $form->field($model, 'id')->dropDownList($dataCountry,
['prompt'=>'-Choose a Name-',
'class'=>'adjust',
'onchange'=>'
$.post("'.Yii::$app->urlManager->createUrl('city/lists?id=').
'"+$(this).val(),function( data )
{
$( "select#city" ).html( data );
});
']);
$dataPost=ArrayHelper::map(\app\models\City::find()->
asArray()->all(), 'id', 'city');
echo $form->field($model, 'id')
->dropDownList(
$dataPost,
['id'=>'city',
'class'=>'adjust'
]
);
ActiveForm::end();
?>
</div>
and after this in another controller for city write following code as:
<?php
namespace app\controllers;
class CityController extends \yii\web\Controller
{
public function actionLists($id)
{
//echo "<pre>";print_r($id);die;
$countPosts = \app\models\City::find()
->where(['country_id' => $id])
->count();
$posts = \app\models\City::find()
->where(['country_id' => $id])
->orderBy('id DESC')
->all();
if($countPosts>0){
foreach($posts as $post){
echo "<option value='".$post->id."'>".$post->city."</option>";
}
}
else{
echo "<option>-</option>";
}
}
}
then run into url it works!
edit: fixed url construction. http requests will now work.
You can do it without any widget manually:
make your activeform as follows:
<?= $form->field($model, 'nameofyourmodel')->dropDownList(
ArrayHelper::map(\app\models\nameofyourmodel::find()->all(), 'id', 'name'),
[
'prompt'=>'smth',
'onchange' => '
$.post(
"' . Url::toRoute('getoperations') . '",
{id: $(this).val()},
function(res){
$("#requester").html(res);
}
);
',
]
); ?>
and here the second form which receives the id from the first model:
<?= $form->field($model,'nameofyourmodel')->dropDownList(
[],
[
'prompt' => 'smth',
'id' => 'requester'
]
); ?>
and the last action is to make a functionality in controller to match 2 ids and send them to your model:
public function actionGetoperations()
{
if ($id = Yii::$app->request->post('id')) {
$operationPosts = \app\models\firstmodel::find()
->where(['id' => $id])
->count();
if ($operationPosts > 0) {
$operations = \app\models\secondmodel::find()
->where(['firstmodelid' => $id])
->all();
foreach ($operations as $operation)
echo "<option value='" . $operation->firstmodelid. "'>" . $operation->name . "</option>";
} else
echo "<option>-</option>";
}
}
The above code is not working properly. There is an error in the line
$.post("'.Yii::$app->urlManager->createUrl('city/lists&id=').'"+$(this).val(),function( data )
console shows the error :
Not Found (#404): Unable to resolve the request: subcategory/lists&id=54
is there any solution for this
my controller looks like below
public function actionLists($id)
{
$posts = SubCategory::find()
->where(['category_id' => $id])
->orderBy('id DESC')
->all();
if($posts){
foreach($posts as $post){
echo "<option value='".$post->id."'>".$post->name."</option>";
}
}
else{
echo "<option>-</option>";
}
}
when i remove the id from the url and hard coded it in to controller it works properly.
I have find a solution for this
please change your view as follows
<?= $form->field($model, 'category_id')->dropDownList($data,['prompt'=>'-Choose a Category-',
'onchange'=>'
$.get( "'.Url::toRoute('product/catlists').'", { id: $(this).val() } )
.done(function( data )
{
$( "select#product-sub_categoryid" ).html( data );
});
']); ?>
and controller like this
public function actionCatlists($id)
{
$mymodel = new Product ();
$size = $mymodel->modelGetCategory ( 'product_sub_category',$id );
if($size){
echo '<option value="">Choose Sub category</option>';
foreach($size as $post){
echo "<option value='".$post['id']."'>".$post['name']."</option>";
}
}
else{
echo '<option value="0">Not Specified</option>';
}
}
don't forget to include this on your view
use yii\helpers\Url;