Yii2: How to add an image as a navbar menuitem - image

i'm trying without success to add an image inside a Navbar menuItem.
It works fine in the brandLabel
But doesn't work on anoter menu item
(I Want to display the logged user image near his name)
I Tryed several times but doesnt seem to make it work,
Would apreciate your help please...
The Code is this:
<?php $this->beginBody() ?>
<div class="wrap">
<?php
NavBar::begin([
'brandLabel' => Html::img('#themes'.'/siteImages/Logo.jpg', ['alt'=>Yii::$app->name]),
'options' => [
'class' => 'navbar-default navbar-fixed-top',
],
]);
// display Login page to guests of the site
if (Yii::$app->user->isGuest) {
$menuItems[] = ['label' => Yii::t('app', 'Login'), 'url' => ['/site/login'],
'options' => [
'class' => 'navbar-right',
],];
}
else
{
// Show sales content to sales+ users
if ( Yii::$app->user->can('useSalesContent'))
{
$menuItems[] = ['label' => Yii::t('app', 'Sales'),
// 'class' => "pull-left",
'url' => Yii::$app->homeUrl,
'linkOptions' => ['id' => 'sales',
'class' => 'navbar-left',
],
];
// Show Admin content to manager+ users
if (Yii::$app->user->can('useAdminContent'))
{
$menuItems[] = ['label' => Yii::t('app', 'Administration'),
'url' => Yii::$app->homeUrl,
'linkOptions' => ['id' => 'admin'],
'options' => [
'class' => 'navbar-left',
],];
}
// display Logout to logged in users
if (!Yii::$app->user->isGuest) {
$menuItems[] =
[
'label' => Yii::t('app', 'Logout'). ' (' . Yii::$app->user-
>identity->username . ')',
'url' => ['/site/logout'],
'linkOptions' => ['data-method' => 'post']
//****** This is where I want the user image to be shown ****//
];
}
}
// echo navbar with selected items
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => $menuItems,
]);
NavBar::end();
?>
<div class="container">
<?= Alert::widget() ?>
<?= $content ?>
</div>
endBody() ?>

Provided the user model has an attribute imageUrl it would be accessible through:
Yii::$app->user->identity->imageUrl
This would become something like:
If you would like to add it to the logout button:
$menuItems[] = [ 'encode'=>false, label' => Yii::t('app', 'Logout'). ' (' . Yii::$app->user- >identity->username . ') ' . Html::img(Yii::$app->user- >identity->imageUrl), 'url' => ['/site/logout'], 'linkOptions' => ['data-method' => 'post']];
make sure you include 'encode' => false,
To add it as a separate item (for instance, to give it a different link):
$menuItems[] = [ 'encode' => false, 'label' => Html::image(Yii::$app->user- >identity->imageUrl)];
Edit:
Make sure you include the Html with a use statement in your view, or provide the full namespace declaration with Html class.

Related

CakePHP 3 : Retrieving data from database using Ajax

I am working on a CakePHP 3 project which is having a Apply Coupon form.
I want to apply the coupon using Ajax.
The view of coupon form is
<?= $this->Form->create(null, [
'url' => ['controller' => 'Coupons', 'action' => 'checkCoupon'],
'name' => 'checkCoupon'
]) ?>
<?= $this->Form->input('coupon_code', [
'type' => 'text',
'placeholder' => 'Apply Coupon Code',
'label' => false
]) ?>
<?= $this->Form->submit('Apply Coupon') ?>
and the checkCoupon action in CouponsController is
public function checkCoupon()
{
$this->request->onlyAllow('ajax'); // No direct access via browser URL
if ($this->request->is('post')) {
$couponCode = $this->request->data['coupon_code'];
$couponCheck = $this->Coupons->find('all', [
'conditions' => [
'coupon_code' => $couponCode
]
]);
if ($couponCheck->count() === 1) {
$coupon = $couponCheck->first();
$valid_till = $coupon->valid_till;
$dt = new Time($valid_till);
$date = $dt->format('Y-m-d');
if ($date >= date('Y-m-d')) {
echo 'Coupon is Valid. Discount of '.$coupon->value.'has been applied';
} else {
echo 'Coupon is Expired';
}
} else {
echo 'This is not a valid coupon code';
}
}
}
I want the $coupon->value and $coupon->id to be retrieved and added to the checkout link as
<?= $this->Html->link(__('Confirm Checkout'), ['controller' => 'ServiceRequests', 'action' => 'confirmCheckout', $service->id, $primaryAddressId, $serviceArea->id, $coupon->id], ['class' => 'btn btn-block btn-success']) ?>
The Apply Coupon form is in checkout action of RequestsController
Also the form is working well. I have checked it by removing the onlyAllow('ajax') line and printing values in check_coupon.ctp view.
How could I do it using Ajax ?
Edit 2 : checkout.ctp
<div class="form-info coupon">
<?= $this->Form->create(null, [
'url' => ['controller' => 'Coupons', 'action' => 'ajax_checkCoupon'],
'name' => 'checkCoupon',
'id' => 'checkCoupon'
]) ?>
<?= $this->Form->input('coupon_code', [
'type' => 'text',
'placeholder' => 'Apply Coupon Code',
'label' => false
]) ?>
<label class="hvr-sweep-to-right">
<?= $this->Form->submit('Apply Coupon', ['id' => 'applyCoupon']) ?>
</label>
<label id="couponUpdate"></label>
<label id="loading" style="display:none;">Loading...</label>
<?php
$data = $this->Html->script('#checkCoupon')->serializeForm(['isForm' => true, 'inline' => true]);
$this->Html->script('#checkCoupon')->event(
'submit',
$this->Html->script(
[
'controller' => 'Coupons',
'action' => 'ajax_checkCoupon'
],
[
'update' => '#couponUpdate',
'data' => $data,
'async' => true,
'dataExpression' => true,
'before' => "$('#loading').fadeIn();$('#applyCoupon').attr('disabled','disabled');",
'complete' => "$('#loading').fadeOut();$('#applyCoupon').removeAttr('disabled');"
]
)
);
?>
</div>
Error : Call to a member function serializeForm() on string on line 18 in checkout.ctp

Fetch and display dropdown selected value in codeigniter

I wanted to fetch the selected value from the database and display it in codeigniter form_dropdown() function but it displays wrong.
Controller:
$type = array(
'options' => array(
'section' => 'Section',
'transaction' => 'Transaction',
'document' => 'Document'
),
'attributes' => array(
'class' => 'form-control'
)
);
View:
<?php echo form_dropdown('type', $type['options'],'', $type['attributes']) ?>
The Screenshot
Try the below code:
Controller:
$this->data['type'] = array(
'name' => 'type_value',
'attributes' => 'class="form-control"',
'value' => (isset($database_type_value) && trim($database_type_value)) ? $database_type_value: $this->input->post('type_value',TRUE), //$database_type_value - value from database
'options_list' => array(
'section' => 'Section',
'transaction' => 'Transaction',
'document' => 'Document'
),
);
View:
<?php echo form_dropdown($type['name'],$type['options_list'],$type['value'],$type['attributes']);?>

dependent dropdown when edit in yii

Problem in dependent dropdowns when editing in my yii application.
While editing, the drop downs are not automatically selected.
In my view,
array('class' => 'CButtonColumn',
'header' => 'Manage',
'template' => '{update} {view} {delete}',
'htmlOptions' => array('width' => '20%'),
'buttons' => array(
'update' => array(
'label' => '',
'imageUrl' => '',
'options' => array('class' => 'glyphicon glyphicon-pencil'),
),
'view' => array(
'label' => '',
'imageUrl' => '',
'options' => array('class' => 'glyphicon glyphicon-eye-open'),
),
'delete' => array(
'label' => '',
'imageUrl' => '',
'options' => array('class' => 'glyphicon glyphicon-remove'),
),
),
),
<div class="form-group">
<label for="reg_input" class="req">Course</label>
<?php
$course = CHtml::listData(Course::model()->findAll(), 'courseid', 'course_name');
echo CHtml::activeDropDownList($model, 'courseid', $course, array(
'empty' => 'Select Course', 'class' => "form-control",
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('Assignment/Fetchbatch'),
'update' => '#' . CHtml::activeId($model, 'batchid'))));
?>
<?php echo $form->error($model, 'courseid', array('class' => 'school_val_error')); ?>
</div>
<div class="form-group">
<label for="reg_input" class="req">Batch</label>
<?php
$batch = CHtml::listData(Batch::model()->findAll(), 'batchid', 'batch_name');
echo $form->dropDownList($model, 'batchid', $batch, array('prompt' => 'Select Batch',
'class' => "form-control",
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('Assignment/Fetchsubject'),
'update' => '#' . CHtml::activeId($model, 'subjectid'))));
echo $form->error($model, 'batchid', array('class' => 'school_val_error'));
?>
</div>
Second dropdown get the data, to change of first dropdown. At this condition the dropdown will not be selected automatically. Because when editing, that value is not there. So I fixed this problem, my code is above this.

codeigniter bootstrap modal popup

I have used bootstrap modal popup in my site. By clicking the button pop will open. It is working on the following code.
HTML:
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
But the button come from array.
<?php
$args['test'] = array(
array(
'type' => 'submit',
'id' => ' text',
'label' => 'Launch demo modal',
'desc' => site_url('test'),
'class' => 'span3',
'default' => '',
'options' => ''),
);
?>
How can I pass "data-toggle="modal" data-target="#myModal" in array.
Nothing different, just add those attributes in the array like this:
array(
'type' => 'submit',
'id' => ' musicfileupload',
'label' => 'Launch demo modal',
'desc' => site_url('test'),
'class' => 'span3',
'default' => '',
'options' => '',
'data-toggle' => 'modal', // <--
'data-target' => '#myModal' // <--
);
Update: Following is a working example:
$data = array(
'type' => 'submit',
'id' => ' musicfileupload',
'label' => 'Launch demo modal',
'desc' => site_url('test'),
'class' => 'span3',
'default' => '',
'options' => '',
'data-toggle' => 'modal', // <--
'data-target' => '#myModal' // <--
);
echo form_button($data);

Validation Errors not showing

I am trying to validate a user when they register to my application. Nothing is getting set to validationErrors, which is strange can anyone help me out?
Here is my MembersController
<?php
class MembersController extends AppController {
var $name = 'Members';
var $components = array('RequestHandler','Uploader.Uploader');
function beforeFilter() {
parent::beforeFilter();
$this->layout = 'area';
$this->Auth->allow('register');
$this->Auth->loginRedirect = array('controller' => 'members', 'action' => 'dashboard');
$this->Uploader->uploadDir = 'files/avatars/';
$this->Uploader->maxFileSize = '2M';
}
function login() {}
function logout() {
$this->redirect($this->Auth->logout());
}
function register() {
if ($this->data) {
if ($this->data['Member']['psword'] == $this->Auth->password($this->data['Member']['psword_confirm'])) {
$this->Member->create();
if ($this->Member->save($this->data)) {
$this->Auth->login($this->data);
$this->redirect(array('action' => 'dashboard'));
} else {
$this->Session->setFlash(__('Account could not be created', true));
$this->redirect(array('action' => 'login'));
pr($this->Member->invalidFields());
}
}
}
}
}
?>
Member Model
<?php
class Member extends AppModel {
var $name = 'Member';
var $actsAs = array('Searchable');
var $validate = array(
'first_name' => array(
'rule' => 'alphaNumeric',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter your first name'
),
'last_name' => array(
'rule' => 'alphaNumeric',
'required' => true,
'allowEmpty' => false,
'message' => "Please enter your last name"
),
'email_address' => array(
'loginRule-1' => array(
'rule' => 'email',
'message' => 'please enter a valid email address',
'last' => true
),
'loginRule-2' => array(
'rule' => 'isUnique',
'message' => 'It looks like that email has been used before'
)
),
'psword' => array(
'rule' => array('minLength',8),
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a password with a minimum lenght of 8 characters.'
)
);
var $hasOne = array('Avatar');
var $hasMany = array(
'Favourite' => array(
'className' => 'Favourite',
'foreignKey' => 'member_id',
'dependent' => false
),
'Friend' => array(
'className' => 'Friend',
'foreignKey' => 'member_id',
'dependent' => false
),
'Guestbook' => array(
'className' => 'Guestbook',
'foreignKey' => 'member_id',
'dependent' => false
),
'Accommodation'
);
var $hasAndBelongsToMany = array('Interest' => array(
'fields' => array('id','interest')
)
);
function beforeSave($options = array()) {
parent::beforeSave();
if (isset($this->data[$this->alias]['interests']) && !empty($this->data[$this->alias]['interests'])) {
$tagIds = $this->Interest->saveMemberInterests($this->data[$this->alias]['interests']);
unset($this->data[$this->alias]['interests']);
$this->data[$this->Interest->alias][$this->Interest->alias] = $tagIds;
}
$this->data['Member']['first_name'] = Inflector::humanize($this->data['Member']['first_name']);
$this->data['Member']['last_name'] = Inflector::humanize($this->data['Member']['last_name']);
return true;
}
}
?>
login.ctp
<div id="login-form" class="round">
<h2>Sign In</h2>
<?php echo $form->create('Member', array('action' => 'login')); ?>
<?php echo $form->input('email_address',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('psword' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Password')
))?>
<?php echo $form->end('Sign In');?>
</div>
<div id="signup-form" class="round">
<h2>Don't have an account yet?</h2>
<?php echo $form->create('Member', array('action' => 'register')); ?>
<?php echo $form->input('first_name',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('last_name',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('email_address',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('psword' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Password')
))?>
<?php echo $form->input('psword_confirm' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Confirm'),
'div' => array('style' => ''),
'type' => 'password'
))?>
<?php echo $form->end('Sign In');?>
</div>
I believe your problem is here:
$this->redirect(array('action' => 'login'));
pr($this->Member->invalidFields());
The validation errors are designed to show on the form, underneath the appropriate field. However, instead of continuing and trying to display the form, you are redirecting the user to a different page.
If you remove the two lines above, it should show the validation errors beneath their fields on the form when the validation fails.

Resources