I want the items in my SideNav by Kartik in the yii2 app to change the color when it is active(was clicked and open).
Sorry, I am pretty new for PHP and Yii and the question might be seen obvious but I really stack here.
I have already tried to use the "active" option that is explained in the documentation but it doesn't work. It doesn't show any error but is not working. I have a file adminMenu.php where the SideNav is written. and the panel.php view file where I showing it.
Also, I tried to add echo
$this->render('adminMenu'['currentPage'=>'admin/personal']);
but it shows error and thus I comment it for now.
adminMenu.php:
class adminMenu extends Widget{
public function init(){
$curentpage = Yii::$app->controller->id ;
parent::init();
ob_start();
echo SideNav::widget([
'type' => SideNav::TYPE_PRIMARY,
'headingOptions' => ['class'=>'head-style'],
'items' => [
['label' => 'Personal',
'url' => ['/admin/personal'],
'active' => ($curentpage == 'admin/personal')],
['label' => 'Clients',
'url' => ['/admin/clients'],
'active' => ($curentpage == 'admin/clients')],
...
]);
panel.php:
if(\Yii::$app->user->can('Admin')){
echo adminMenu::widget();
//echo $this->render('adminMenu'['currentPage'=>'admin/personal']);
}
i think that you mistake is in this line
$curentpage = Yii::$app->controller->id;
Yii::$app->controller->id only return the name of your controller , in this casi will be "admin" then you compare "admin" equals "controller/action" ('admin/personal') this never will be equals .
To do this , you can do a concat the actual controller and the actual action like this :
$curentpage = Yii::$app->controller->id.'/'.Yii::$app->controller->action->id;
and the comparation will be success and the "active" class add to you sidebar
Related
I have a gii generated view.php page, which can be reached from two different paths, but the breadcrumbs is the same. Anyone know how to fix?
Let me explain: I have the view.php view which shows the summary of the report made and can be reached from two paths:
when I create a new report and therefore the path should be HOME / CREATION / VIEW;
and also from a section that shows the user the summary of the reports she sent and therefore the breadcrumbs should be HOME / SUMMARY / VIEW.
You have 2 options to know where it came from:
Send a query variable on each link or in the redirection to manually build the breadcumb. Like: $value = Yii::$app->request->getQueryParam('breadcumb')
Other option is to get the referrer url. And base on the value you can pass it to the switch. You can get referrer's url using: $value = Yii::$app->request->getReferrer().
Then do a switch to build the link:
switch(value) {
case 'creation':
$label = 'CREATION';
$url = 'url_of_creation';
break;
case 'summary':
$label = 'SUMMARY';
$url = 'url_of_summary';
break;
}
Then just do something like this:
$this->params['breadcrumbs'][] = ['label' => $label, 'url' => $url];
This is a short breadcrum solution using match():
$this->params['breadcrumbs'][] = match($path) {
'creation' => ['label' => 'Creation', 'url' => Url::to['creation'],
'summary' => ['label' => 'Summary', 'url' => Url::to['summary'],
};
$path should either be set in the controller or determined by Yii::$app->request->getReferrer().
Please note, that this requires PHP8.
I have a dataprovider to search a world but my listview does not display any record? How can i send this query object to listview?
every thing in my webpage is worked very good but at the output my list view show "not found any result" this mean my list view code is no have problem . problem is in my dataprovider and this query beacuse i customize that
my controller:
$query = new Query();
$dataProvidersearch=new ActiveDataProvider([
'query'=>$query->from('tbl_post')->Where(['like', 'title', $search])-
>andWhere(['like', 'en_title', $search])->andWhere(['like', 'content', $search])->andWhere(['like', 'en_content', $search]),
]);
this is my list view in my view:
$posts = $model->getModels();
echo ListView::widget([
'dataProvider'=>$posts,
'itemView'=>'search',
'summary' => '',
'itemOptions' => [
'tag' => false
],
]);
I'm not sure you have enough code here for someone to help. Even something simple like a listview could consist of a view, a controller, and two model files and your code could be failing at any of these points. You may have simply forgot to include the listview library at the top of your view, but we can't see that in your current example.
What I would recommend is using Gii to generate a listview. It is simple to do and once you have it created, you can study the code to see where you went wrong. You can see how to get started generating code with Gii here: http://www.yiiframework.com/doc-2.0/guide-start-gii.html
ANSWER FROM COMMENTS: Replace andWhere with orWhere, no results are found because no record can match 'title' and 'en_title' and 'content' and 'en_content'.
You are submitting $posts as 'dataProvider' while it should be dataProvidersearch
Instead of:
$posts = $model->getModels();
echo ListView::widget([
'dataProvider'=>$posts,
'itemView'=>'search',
'summary' => '',
'itemOptions' => [
'tag' => false
],
];
Should be:
$posts = $model->getModels();
echo ListView::widget([
'dataProvider'=>$dataProvidersearch,
'itemView'=>'search',
'summary' => '',
'itemOptions' => [
'tag' => false
],
];
In a projects/create active form I have a field "related company account" as a dropdown (select2 by kartik). Behind this field I'd like to place a plus sign or something else to add new accounts to the dropdown with the following behavior:
gather all input done so far (like $input = compact(array_keys(get_defined_vars())); but probably needed on client side)
jump to accounts/create and pass $input
after submiting the new account jump back to projects/create (e.g. return $this->redirect(Yii::$app->request->referrer);) and fill the previously entered data (extract($input, EXTR_PREFIX_SAME, "arr");)
I'm struggling now with several issues:
Is this process according to best practice or should I change something fundamentally?
How is the button like? Submit button, link or some form of javascript?
Problem with Submit button is that not all required fields may be filled. So saving and resuming/updating the project model might not be possible.
Problem with link is that it is constructed before data was entered
Problem with javascript is that I have no glue
Any hints are welcome. Thank you in advance.
One alternative i would suggest is using Session.
As for the "Add Accounts" button, i would use Submit button, and give different name to actual Submit button (two submit button in form, as answered in here). So, the projects/create view will look like this :
<?php $form = ActiveForm::begin(); ?>
...
...
...
<?= $form->field($model, 'account_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Account::find()->all(), "id", "name"),
'options' => ['placeholder' => 'Select a related company account ...'],
'pluginOptions' => [
'allowClear' => true
],
]) ?>
<?= Html::submitButton('Add Account ;)', ['class' => 'btn btn-success', 'name' => 'add_account_submit']) ?>
...
...
...
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
And then check in ProjectsController, which submit button pressed by user. If add account was pressed, then save the inputed field (i would put this function in model for clearance), else, save the model or anything. And, before all that, check if session about project is set, if yes then pre-load it to model (again, in model). Okay, like they say, one code is worth a thousand words, so, this is ProjectsController will look like :
class ProjectsController extends Controller
{
...
...
...
public function actionCreate($category)
{
$model = new Projects();
if (Projects::isSavedInSession()) {
$model->loadFromSession();
}
if (Yii::$app->request->post('add_account_submit')) { // if add_account_submit is clicked
$model->saveTosession(Yii::$app->request->post('Projects')); // I assume your model named Projects, if not, change this value to your model name
return $this->redirect(['accounts/create']);
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->clearSession(); // we dont need the session anymore
return $this->redirect(['index');
}
return $this->render('create', [
'model' => $model,
]);
}
...
...
...
}
And Projects model will look like :
class Projects extends \yii\db\ActiveRecord
{
...
...
...
public static function isSavedInSession() { // why this is static is beyond this question context
if (Yii::$app->session->get('projects')) return true;
return false;
}
public function loadFromSession() {
if (Yii::$app->session->get('projects_name')) $this->name = if (Yii::$app->session->get('projects_name'));
if (Yii::$app->session->get('projects_account_id')) $this->account_id = if (Yii::$app->session->get('projects_account_id'));
...
... // insert all model's field here
...
}
public function saveToSession($fields) {
Yii::$app->session->set('projects', 1);
foreach ($fields as $field=>$value) {
Yii::$app->session->set('projects_' . $field, $value);
}
}
public function clearSession() {
Yii::$app->session->remove('projects'));
Yii::$app->session->remove('projects_name'));
Yii::$app->session->remove('projects_account_id'));
...
... // insert all model's field here
...
}
...
...
...
}
And in the AccountsController, just tell the program to jump back to projects/create if projects session is set, like so :
class AccountsController extends Controller
{
...
...
...
public function actionCreate($category)
{
$model = new Accounts();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
if (Projects::isSavedInSession()) {
return $this->redirect(['projects/create');
}
return $this->redirect(['index');
}
return $this->render('create', [
'model' => $model,
]);
}
...
...
...
}
Well, it's looks bit lengthy, but yeah, it's worth trying. Anyway, you could use this approach for another purpose, save current form state for example.
Oh, one more thing, i haven't tested this in real code, so if any error exposed on my code, hit me up in comment.
Happy coding. :)
Hi everyone i am using FileInput kartik widget in yii2 project and uploading and saving works fine but i am having problem while updating the images
I can get the images path on the update form and create and array and display in as initialpreview in the widget but the problem is that my files field is required field so even there are some values in initialpreview the form gives error to upload image as its required field. So what should i do here?
I only want to give preview of their uploaded pics to the user but if they dont make any changes than i dont want to update anything for images
Following is my view code and model code
return [
[[ 'price', 'created_date', 'created_by', 'updated_date', 'updated_by','file','address'], 'required'],
[['price'], 'number'],
[['address'], 'string', 'max' => 255],
[['file'], 'file', 'extensions'=>'jpg, gif, png', 'maxFiles' => 4],
];
<?php
$initalpreview = array();
foreach($model->adsImages as $images) {
$initalpreview[] = Html::img('/upload/'.$images->image, ['class'=>'file-preview-image']);
}
?>
<?=$form->field($model, 'file[]')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*',
'multiple'=>true],
'pluginOptions' => [
'maxFileCount' => 5,
'initialPreview'=> $initalpreview,
'showUpload' => false,
]
]); ?>
So what should i do here?
Thank you
try this
In Model create a scenario named 'update' and mention the fields that are required when update action works
return [
[['price', 'created_date', 'created_by','updated_date','updated_by','address'], 'required', 'on' => 'update'],
];
Now inside controller action update call the scenario
public function actionUpdate(){
//Model Declaration
$model->scenario = 'update';
// update code
}
I have several fields in my form that i wish to post to the database. All the other fields bar the dropdown field are all working fine
The official documentation for zend 2 is not really clear on how to deal with posting data from a dropdown menu into the database
Here's what i have:
my addAction in the controller
public function addAction()
{
$form = new UsersForm();
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost())
{
$users = new Users();
$form->setInputFilter($users->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid())
{
$users->exchangeArray($form->getData());
$this->getUsersTable()->saveUser($users);
// Redirect to list of albums
return $this->redirect()->toRoute('index');
}
}
return array('form' => $form);
}
my form
public function __construct($name = null)
{
// we want to ignore the name passed
parent::__construct('users');
//other form elements...
//the dropdown menu
$this->add(array(
'type' => 'Select',
'name' => 'groupid',
'options' => array(
'label' => 'Group',
'value_options' => array(
'0' => 'Not Selected',
'1' => 'Super Admin',
'2' => 'Company Admin',
),
),
));
//...
}
}
the view
<?php
$form->setAttribute('action', $this->url('user', array('action' => 'add')));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formRow($form->get('groupid'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
When i run my application for the addAction, i get an error message:
Statement could not be executed (23000 - 1048 - Column 'GroupID' cannot be null)
where 'GroupID' is the column in my table that takes the value from the dropdown which means the field is not being posted
I need help on this
If the column in your database is GroupID, the form element should also be named that. Yours is groupid (i.e. lowercase). If that doesn't fix the issue, please edit your question to include the DB structure and the code for the saveUser() function.