yii2 not rendering to view just refreshing the page - model-view-controller

view.php code part:
View Picture
viewgood.php
<?php
echo 'hello';
GoodsController.php
public function viewgood($id = null) {
}
After clicking on button View Picture my page just refreshing instead of going to viewgood.php
What am I doing incorrectly?
I am a begginer in Yii2

Try use
View Picture
in a anchor tag html your need use the complete route, for use shortcut you try use
<?= Html::a('View Picture', ['/goods/viewgood/', 'id' => $good['GoodGallery'][0]['id']], ['class' => 'btn btn-primary']) ?>

view.php
You can use Html:a(), or in your example use Url helper to() function to generate the proper route for your anchor tag.
View Picture
GoodsController.php
public function actionViewgood($id=null){
//fetch the data e.g.
$model = Good::findOne(id);
//Do some extra code checking when no record is found like throw an exception or set a flash error message, etc.
//render the viewgood and pass the data (if needed)
return $this->render('viewgood', [
'model' => $model
]);
}
viewgood.php
<?php
//do what you want with the data passed by the controller. E.g. print the name of the good (if applicable)
echo $model->name;
//your other code ...
?>

Related

Ckeditor getdata() function is not working in laravel

I used withinput() function to return back with form values but it's not working for ckeditor, that's why I tried getting value with Ckeditor getdata() function but it's also didn't work.
Ckeditor Form is like:
<?php echo Form::text("PageLanguage[description][$language>id]",
old("PageLanguage[description][$language->id]"),
array('id' =>"description-$language->id",'class' => 'form-control'));
?>
Any ideas?
I used textarea and it worked in my code
If you use Form::text it can't get value that's why it will save null value, you must change Form::text to Form::textarea like that:
<?php echo Form::textarea("PageLanguage[description][$language->id]",
old("PageLanguage[description][$language->id]"),
array('id' =>"description-$language->id",'class' => 'form-control'));?>

Yii2 images to have checkbox list in the search form

In my yii2 project I want to get checkbox for my images in order to search by images. Whenever the users checks the checkbox and submits the button, it should display the content only with those checked images.
My checkbox list
<?php $img = ArrayHelper::map(app\models\GhsPictogram::find()->all(), 'pictogram_id', 'pictogram_filepath') ?>
<?= $form->field($model, 'ghsPictogram',['template'=>'<div class="ghs-pict"> {label}{input} </div>'])->checkboxList($model->imageList($img)) ?>
My imageList method in my model
public function imageList($filenames) {
$imageList = [];
foreach ($filenames as $key => $value) {
$imageList[$key] = Html::img(
Yii::$app->request->baseUrl . 'web' . $value,
'', array("style"=>"width: 50px")
);
}//foreach $filenames
return $imageList;
}
But In my form it doesn't display the image. It instead displays the image src.
I have attached my output:
Help me find How can I display image in the search form field. Thank you
Checkbox list has an option called encode, which default to true and it encodes (as it says) html that is passed to it.
To solve it, just add 'encode' => true to checkboxList options property, like this:
<?= $form->field($model, 'ghsPictogram',['template'=>'<div class="ghs-pict"> {label}{input} </div>'])->checkboxList($model->imageList($img), [
'encode' => false
]) ?>

How to implement model validation on autocomplete field in yii2?

I am using a jui autocomplete widget in my form. Model validation is not working properly in here.
This is my view
<?php $form = ActiveForm::begin();?>
<div class="members-form">
<div class="col-md-5">
<?php
$data = FamilyName::find()
->select(['name as value', 'name as label','id as id'])
->asArray()
->all();
echo 'Family Name' .'<br>';
echo AutoComplete::widget([
'name' => 'family',
'id' => 'family_name',
'clientOptions' => [
'source' => $data,
// 'minLength'=>'3',
'autoFill'=>true,
'select' => new JsExpression("function( event, ui ) {
$('#members-family_name_id').val(ui.item.id);//#City-state_name is the id of hiddenInput.
}")],
]);
?>
<?= Html::activeHiddenInput($model, 'family_name_id')?>
<?= $form->field($model, 'remarks')->textInput() ?>
<?php ActiveForm::end(); ?>
</div>
</div>
my model code
public function rules()
{
return [
[['family_name_id', 'first_name',
'date_of_birth', 'relation_id', 'is_head','marital_status','remarks',
'gender','address_id'], 'required'],
];
}
Now if i try to create a new member with no data selected in any of the fields, then required fields will show like " ... cannot be blank" in red. But the family_name_id is not showing such validation. The data is not getting saved if leave the auto complete field empty but no validation message is being displayed. How can i show validation messages with jui auto complete ?
I believe you faced the same problem as I had few weeks ago. I experienced similar behavior: I saw autocomplete suggestions and could interact with them, but when I left the input field the client-site validation kept silent.
If you look at the html produced by your view, at the bottom you can see some javascript code, which is responsible for the client-side validation. It looks like:
jQuery(document).ready(function () {
....
jQuery('#app-new-form').yiiActiveForm(
[
{
"id":"application-familyname",
"name":" familyname ",
"container":".field-application-familyname",
"input":"#application-familyname",
"enableAjaxValidation":true,
"validate":function (attribute, value, messages, deferred, $form) {
yii.validation.required(value, messages, {"message":"Field cannot be empty"});
}
}
], []);
.....
});
This code assigns an event handler to your autocomplete field to start the client-side validation. But you have to pay attention, which id is used for the field. Unfortunately, yii2 takes the id provided by you only to construct the <input> element in html. When it produces javascript code the id is always generated from few permanent parts. The most important two are the name of the model and the name of the attribute. In your case id should be something like 'your_modelname -family_name_id'.
Because your explanation is not complete, this is only a guess. So, look at your html source and be sure you have the same id for the input you try to validate and the id in the JavaScript (see above).
You are using Html Hidden Input .. You have to use ActiveForm HiddenInput to show error validation..
use
<?= $form->field($model, 'family_name_id')->hiddenInput()->label(false);>
Why don't you use the family_name_id instead of creating a new select?
<?= $form->field($model, "family_name_id")->dropDownList(
ArrayHelper::map(FamilyName::find()->all(), 'id', 'name'),
['prompt' => 'Select']
) ?>
And you can change the label by using ->label('Family Name'), but i would recommend changing in model (unless you need "Family Name Id" as a label elsewhere).
I know you didn't said anything about that, but can i recommend you to see this answer about using methods that perform sql queries inside your view?

Yii ClinkPager doesn't work on Ajax Request

Firstly, when the page gets loaded, ClinkPager works properly with all the paging correctly displayed.
But when Ajax Request is sent, the results get populated correctly with all the paging.
But clicking on the next or another page in the Paging, the previous data gets loaded and also paging shows different sequence.
/*Controller action to fetch the records and apply the pagination*/
//---------------------------------------------------------------
public function actionGetUser($user_id=null)
{
$user_domain= (isset($_POST['user_domain'])?$_POST['user_domain']: null);
$model=new UserSearch();
$criteria=new CDbCriteria();
//If Category/Title are also specified for search, then its an Ajax request.
if((isset($_POST['ajax_search'])) && ($_POST['ajax_search']==1))
{
//Change the search criteria accordingly
$criteria->select="*";
if($user_domain!= null)
{
//Adding criteria to search for ideas of specific domain
$criteria->addCondition("user_domain=".$usr_domain);
}
}
//Retrieve the users.
$searchData = $model->search();
//Count the no. of results retrieved.
$count=UserSearch::model()->count($criteria);
//Enable pagination
$pages=new CPagination($count);
$searchData->setPagination($pages);
$pages->applyLimit($criteria);
//Search for ideas satisfying that criteria
$models=userSearch::model()->findAll($criteria);
if((isset($_POST['ajax_search'])) && ($_POST['ajax_search']==1))
{
//Rendering the respective page
$this->renderPartial('renderOnAjax', array(
'user' => $models,
'pages' => $pages,
'user_count'=>$count
));
}
else
{
//Rendering the respective page
$this->render('render', array(
'user' => $models,
'pages' => $pages,
'user_count'=>$count
));
}
}
//------------------------------------------------------------
/*render page*/
//------------------------------------------------------------
<div>
<div class="userInfo" id="user_search_result">
<?php $this->renderPartial("renderOnAjax",array('user'=>$user, 'pages'=>$pages));?>
</div>
</div>
//------------------------------------------------------------
/*renderOnAjax Page*/
//------------------------------------------------------------
<?php
$i=0;
$count=count($user);?>
<?php while($i!=$count) {?>
<?php $row=$count[$i];?>
<div class="Box">
/*Some contain to display...*/
</div>
<?php $i++;?>
<?php } ?>
<div class="row">
<?php $this->widget('CLinkPager', array(
'pages' => $pages
));
?>
</div>
//---------------------------------------------------------
try
<?php $this->renderPartial("renderOnAjax",array('user'=>$user, 'pages'=>$pages),false,true);?>
Here is official documentioan for renderPartial
public string renderPartial(string $view, array $data=NULL, boolean $return=false, boolean $processOutput=false)
$view=string name of the view to be rendered. See getViewFile for details about how the view script is resolved.
$data=array data to be extracted into PHP variables and made available to the view script
$return=boolean whether the rendering result should be returned instead of being displayed to end users
$processOutput=boolean whether the rendering result should be postprocessed using processOutput.
{return} string the rendering result. Null if the rendering result is not required.
EDIT:
The above scheme works for ajax call renderPArtials. You should try this where you are rendering ajax request in controller action like
$this->renderPartial('renderOnAjax', array(
'user' => $models,
'pages' => $pages,
'user_count'=>$count
),false,true);

Drupal 7 - Ajax and Bootstrap - Rerender Main Menu on Login

How can I rerender the main menu in Drupal after an Ajax Login?
I already tried the following (generating the return value in my PHP Ajax Controller):
$tree = menu_tree_all_data('main-menu');
$returnValue = drupal_render(menu_tree_output($tree));
However this will not include the Bootstrap specific class names. It basically just returns a minimalistic menu structure without anything added by the theme.
In the Bootstrap theme, the menu is rendered like this:
<?php if (!empty($primary_nav)): ?>
<?php print render($primary_nav); ?>
<?php endif; ?>
<?php if (!empty($secondary_nav)): ?>
<?php print render($secondary_nav); ?>
<?php endif; ?>
How can I enforce this type of rendering from my module?
Since I am working on an ajax one pager site, I need to update the menu based on a user's role after login. A page reload would destroy the desired look and feel, and is therefore no option.
Currently I am using the following code to process the login:
function wr_pages_form_alter(&$form, $form_state, $form_id) {
if ($form_id == 'user_login_block' || $form_id == 'user_login') {
$form['actions']['submit']['#ajax'] = array(
'callback' => 'wr_login_form_callback',
'wrapper' => 'user-login',
'method' => 'replace',
'effect' => 'fade',
'event' => 'click'
);
}
}
function wr_login_form_callback($form, $form_state) {
if (!form_get_errors()) {
return "<script>adjustViewsAndMenu();</script>";
}
else {
return $form;
}
}
adjustViewsAndMenu() makes changes to the menu, and adds extra parts to the one pager, depending on a user's role, however this function does not use any Drupal rendering, which is most likely not the best way to deal with this problem. Still haven't found out how to rerender a menu with AJAX while using the theme's rendering.

Resources