How to add span to a label using $form->labelEx from Yii? - yii

I wish to generate the following markup:
<label>some label here <span>(optional)</span></label>
Is there a way to do this, by using Yii labelEx or just label?
Thanks

If the attribute is required
You can set the CHtml static properties like this
CHtml::$beforeRequiredLabel = '';
CHtml::$afterRequiredLabel = '<span>(optional)</span>';
Yii will generate a tag
<label>CHtml::$beforeRequiredLabel.$label.CHtml::$afterRequiredLabel</label>
but the static properties will effect all labels generated by $form->labelEx() (#see CHtml::activeLabelEx())
if you don't need, you must set the static properties to default
If the attribute is not required
you can set the htmlOptions
$form->labelEx($model, $attribute, array('label' => 'your label'))

It's simple, make use of the Decorator pattern:
<?php
// components/CustomCHtml.php
class CustomCHtml extends CHtml
{
public static function activeLabelEx($model,$attribute,$htmlOptions=array())
{
if (isset($htmlOptions['optional']) && $htmlOptions['optional']) {
if (isset($htmlOptions['label']) && $htmlOptions['label']) {
$htmlOptions['label'] .= $htmlOptions['optional'];
} else {
$htmlOptions['label'] = $htmlOptions['optional'];
}
}
return parent::activeLabelEx($model,$attribute,$htmlOptions);
}
}
use case:
<?php echo CustomCHtml::activeLabelEx($model, 'field', array('optional'=>' <span>(optional)</span>')); ?>

Here is a little hack to make it possible.
<?php
$username = $form->field($model, 'username')
->input('text', ['class' => 'form-control input-lg'])
->label(true, 'username', ['class' => 'fa fa-user signin-form-icon']);
$username->parts['{label}'] = '<span class="fa fa-user signin-form-icon">dwe</span>';
echo $username;
?>

You could use CHtml::$afterRequiredLabel and/or CHtml::$beforeRequiredLabel
$initValue = CHtml::$afterRequiredLabel;
CHtml::$afterRequiredLabel = $initValue.'<span>(optional)</span>';
echo $form->labelEx($model, $fname, array('class' => ''));
echo $form->textField($model, $fname, array('class' => ''));
CHtml::$afterRequiredLabel = $initValue;
This way the label will be applied only on the specified form field. You actually set the initial value of CHtml::$afterRequiredLabel and/or CHtml::$beforeRequiredLabel on a temp variable, you overwrite the value that you need, and then reset it to original value.

Related

Yii framework: how to get id from DB, when choosing related record from DB

I have text edit box with Autocomplete::widget on the web page.
Autocomplete populates from DB. When I start to type and choose Autocomplete item (which is the First Name from DB, in my case) I need to get the associated id from DB. How could this get implemented?
<?php
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use app\models\Rating;
use app\models\Teacher;
use yii\jui\AutoComplete;
use yii\web\JsExpression;
/* #var $this yii\web\View */
/* #var $model app\models\Rating */
/* #var $form ActiveForm */
$data = Teacher::find()
->select(['lname as value', 'lname as label','id as id'])
->asArray()
->all();
//print_r($data[0].id);//exit;
?>
<div class="rating-input">
ФИО
<?php
echo AutoComplete::widget([
'name' => 'Teacher',
'id' =>'ddd',
'clientOptions' => [
'source' => $data,
'autoFill'=>true,
'minLength'=>'1',
],
]);
https://paste.ee/p/BtQav
try this
<input type="hidden" name="teacher_id" id="teacher_id" value="">
<?php
echo AutoComplete::widget([
'name' => 'Teacher',
'id' =>'ddd',
'clientOptions' => [
'source' => $data,
'autoFill'=>true,
'minLength'=>'1',
'select' => new \yii\web\JsExpression("function( event, ui ) {
// $('#teacher_id').val(ui.item.id);//#teacher_id is the id of hiddenInput.
console.log(ui.item.id);
}")
],
]);
You have more information in documentation page : http://www.yiiframework.com/wiki/830/simple-jui-autocomplete-in-yii2/

How to pass variable from actionCreate to _form.php?

I have a create action of controller where I passed $ingredients array into the view
public function actionCreate()
{
return $this->render('create',
['model' => $model, 'ingredients' => Ingredient::find()->all()]
);
}
In create.php I can acess $ingredients variable.
But if I try to access $ingredients in the _form.php
<?= $form->field($model, 'ingredient_id')->checkbox(
ArrayHelper::map($ingredients, 'id', 'name')
) ?>
I get error
Undefined variable: ingredients
This can be done by two ways
//first render the view file like this
$params = [];
$params['eqpType'] = $eqpType;
$params['discountModel'] = $discountModel;
$params['tabActive'] = $tabActive;
$params['discountLabel'] = $discountLabel;
echo $this->render('_form', $params);
//or you can include the code file directly ..in this case do not need to pass all perameters
<?php include_once "_form.php";?>
Your are passing the variables to the create view, and your widget is in another view called _form. Go to the create view and make sure that all variables are passed to the _form view.
in create.php
<?php echo $this->render('_form', [
'model' => $model,
'ingredients' => $ingredients
]) ?>

Is it possible to have 2 different CGridView in one admin.php in Yii?

Is it possible to have 2 different CGridView Tables in one admin.php ?
For example, I have a page of Services and a page of Packages.
Services are basically individual single services whereas Packages consist of individual services.
So, my question is, can I have the Service's CGridView to be displayed in Package/admin.php page? A seperate CGridView table.
Top part with list of Packages, and at the bottom, a different table, with Individual services.
If so, please guide me through it. Thanks in advance.
Updated
public function actionAdmin() {
$model = new Package('search');
$model2 = new Service('search');
$model->unsetAttributes();
$model2->unsetAttributes();
$model->active=1;
$model2->active=1;
if (isset($_GET['Package'])){
$model->setAttributes($_GET['Package']);
}
$this->render('admin', array(
'model' => $model,
'model2' => $model2,
));
}
Under _form.php:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id' => 'service-grid',
'dataProvider' => $model2->search(),
'htmlOptions'=>array('class'=>'grid-view grid-size'),
'filter' => $model2,
'columns' => array( //the appropriate columns
));
Yes this is possible and you can have any number of grid views in one page/action.
here is a example where i display two gridviews, namely Manage Subjects 1 & Manage Subjects 2
<?php
/* #var $this SubjectController */
/* #var $model Subject */
$this->breadcrumbs = array(
Yii::t('edu', 'Subjects') => array('index'),
Yii::t('edu', 'Manage'),
);
?>
<?php echo $this->renderPartial('application.views.layouts._actions', array('model' => $model)); ?>
<?php
Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
$('.search-form').toggle();
return false;
});
$('.search-form form').submit(function(){
$.fn.yiiGridView.update('data-grid', {
data: $(this).serialize()
});
return false;
});
");
?>
<h3><?php echo Yii::t('edu', 'Manage Subjects 1'); ?></h3>
<!-- search-form -->
<div class="search-form" style="display:none">
<p>You may optionally enter a comparison operator (<b><</b>, <b><=</b>, <b>></b>, <b>>=</b>, <b><></b> or <b>=</b>) at the beginning of each of your search values to specify how the comparison should be done.</p>
<?php $this->renderPartial('_search', array('model' => $model)); ?>
</div>
<!-- search-form -->
<?php echo $this->renderPartial('_grid', array('model' => $model)); ?>
<h3><?php echo Yii::t('edu', 'Manage Subjects 2'); ?></h3>
<!-- search-form -->
<div class="search-form" style="display:none">
<p>You may optionally enter a comparison operator (<b><</b>, <b><=</b>, <b>></b>, <b>>=</b>, <b><></b> or <b>=</b>) at the beginning of each of your search values to specify how the comparison should be done.</p>
<?php $this->renderPartial('_search', array('model' => $model)); ?>
</div>
<!-- search-form -->
<?php echo $this->renderPartial('_grid', array('model' => $model)); ?>
Update
you need to create 2 models, see my below code, model2 is created and its a different table. you pass it to admin.php and in the gridview change model to model2 in your second gridview. thats all.
/**
* Manages all models.
*/
public function actionAdmin()
{
$model = new Subject('search');
$model2 = new Institute('search');
Yii::app()->appLog->writeLog('Manage Subjects.'); // Activity log entry
$model->unsetAttributes(); // Clear any default values
$data = TK::get('Subject');
if ($data !== null)
$model->attributes = $data;
$params = array('model' => $model, 'model2' => $model2);
if (Yii::app()->request->isAjaxRequest)
$this->renderPartial('_grid', $params);
else
$this->render('admin', $params);
}

"Object of class Accounts could not be converted to string" in Yii dropDownList

similarly I have 2 tables in database,accounts and banks,and One to Many Relation between them.
'banks' => array(self::BELONGS_TO, 'Banks', 'banks_id'), in Accounts model.
I need to use Chtml::dropDownList in account creation form,so I edit _form.php to it:
<div class="row">
<?php echo $form->labelEx($model,'banks_id'); ?>
<?php echo CHtml::dropDownList($model, 'banks_id', CHtml::listData(Banks::getBanksList(), 'id', 'title','country')); ?>
<?php echo $form->error($model,'banks_id'); ?>
</div>
and also in Banks model develop `getBanksList by:
public static function getBanksList()
{
$userLanguage = Yii::app()->user->getState('lang');
$result = array();
$banks = self::model()->findAll();
foreach ($banks as $bank){
array_push($result, array(
'id' => $bank->id,
'title' => ($userLanguage == $bank->default_lang)?$bank->default_name:$bank->en_name,
'country' => Yii::t('countries',$bank->country),
));
}
return $result;
}
but it raise Object of class Accounts could not be converted to string error ,and in trace it occured at
public static function getIdByName($name)
{
return str_replace(array('[]', '][', '[', ']', ' '), array('', '_', '_', '', '_'), $name);
}
in Chtml.php file.where is the problem?I searched a lot,but I couldn't solve the problem.
I understood where is my problem,I should use $form instead of Chtml.

ZF2 form element description

in ZF1 form and form elements had a setDescription method that was outputted as <p>description here</p> in view ....
ZF2 seems that doesn't have this method
so my question is how can i add description to form elements ?
this is my view :
<div>
<?
$form = $this->form;
$form->prepare();
echo $this->form()->openTag($form);
foreach ($form->getElements() as $el) {
?>
<div class="form_element">
<?=$this->formRow($el);?>
</div>
<?
}
echo $this->partial('system/form/buttons_form_part.phtml', array('form' => $form));
echo $this->form()->closeTag();
?>
</div>
Using ZF 2.1.5, one solution might be setOptions().
In the form definiton:
$file = new Element\File('file');
$file->setLabel('Photo (.jpg, .gif, .png)');
$file->setOptions(array('description' => 'test description'));
…
When rendering the form element:
$element = $form->get(…);
var_dump($element->getOptions());
Will give you access to:
array(1) { ["description"]=> string(16) "test description" }
If you mean a label for an Element you can use the setLabel method when you create the form (in Controller).
$name = new Element('name');
$name->setLabel('Your name');
Or if you use an array to create your form elements use this:
array(
'spec' => array(
'name' => 'name',
'options' => array(
'label' => 'Your name',
),
'attributes' => array(
'type' => 'text'
),
)
),
Here is a link:
enter link description here