Yii2 DepDrop Kartik widget - yii2

I am trying to use the Kartik Depdrop widget. When I select the area field, the firebug console shows the data correctly like:
{"output":[{"id":"6310100000","name":"Харьков"},{"id":"6310400000","name":"Изюм"}],"selected":""}
_form.php
<?= $form->field($model, 'reg')->dropDownList(TReg::getOptions(), ['id' => 'cat-id', 'class'=>'input-large form-control']); ?>
<?= $form->field($model, 'area')->widget(DepDrop::classname(), [
'options'=>['id'=>'subcat-id', 'class'=>'input-large form-control'],
'pluginOptions'=>[
'depends'=>['cat-id'],
'placeholder'=>'Select...',
'url'=>Url::to(['/pt/subcat'])
]
]); ?>
Model
TReg.php
public static function getOptions()
{
$data=static::find()->all();
$value=(count($data)==0)? [''=>'']: \yii\helpers\ArrayHelper::map($data, 'reg_id','reg_name');
return $value;
}
Model TArea.php
public static function getAreaList($reg_id)
{
$data= static::find()->where(['reg_id' => $reg_id])->select(['area_id AS id' , 'area_name AS name'])->asArray()->all();;
$value=(count($data)==0)? [''=>'']: $data;
return $value;
}
Controller
public function actionSubcat() {
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$reg_id = $parents[0];
$out = \common\models\TArea::getAreaList($reg_id);
echo Json::encode(['output' => $out , 'selected' => '']);
return;
}
}
echo Json::encode(['output' => '', 'selected' => '']);
}
What is my mistake? Thanks.

Related

Multiple submitform in update form in yii2

In my Update form, I have two submitform 'Save', 'Save & Submit'. each of them will update particular field.
The submit button looks like -
<?= Html::submitButton('Save',['name'=>'submit', 'value' => 'tello','class' => 'btn btn-primary']) ?>
<?= Html::submitButton('Save & Submit',['name'=>'submit', 'value' => 'hello','class' => 'btn btn-success']) ?>
The best possible Controller Action I got so far is -
if(Yii::$app->request->post('submit')==='tello'){
var_dump("Save is clicked");
die();
}
elseif(Yii::$app->request->post('submit')==='hello'){
var_dump("Submit is clicked");
die();
}
The problem with this is that, I have to click the button twice to submit it. I learned that I have to change the button name to anything but submit. I tried changing it anything else, but it didn't work. It's negelecting the code and proceeds to the next set of code.
I have this two button in create form as well
form
<?= Html::submitButton('Save',['name'=>'Save', 'value' => 'Save','class' => 'btn btn-primary']) ?>
<?= Html::submitButton('Save & Submit',['name'=>'Submit', 'value' => 'Submit','class' => 'btn btn-success']) ?>
Controller action
if ($model->load(Yii::$app->request->post())&& isset($_POST['Save'])){
//do my stuff
}
elseif ($model->load(Yii::$app->request->post())&& isset($_POST['Submit'])){
//do my stuff
}
As asked by scaiseEdge Create Controller Action
public function actionCreatenewworkbasic()
{
$model = new Workpermit();
//$model->wp_validfrom = date('Y-m-d H:i:s');
//$model->wp_validto = date('Y-m-d H:i:s');
$model->wp_timeissued = date('Y-m-d H:i:s');
if ($model->load(Yii::$app->request->post()) && isset($_POST['Save'])) {
//get the instance of the uploaded file
//$jhaName = $model->wp_no;
$model->wp_status = 'Saved';
$timenow = date('-Y-m-d-H-i-s');
$model->jha = UploadedFile::getInstance($model,'jha');
if (!empty($model->jha)) {
$model->jha->saveAs('uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension);
//save the path in the db
$model->wp_jhaattach = 'uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension;
}
$model->jha = null;
$model->save(false);
return $this->redirect(['availablework']);
}
elseif ($model->load(Yii::$app->request->post())&& isset($_POST['Submit']))
{
//get the instance of the uploaded file
//$jhaName = $model->wp_no;
$model->wp_status = 'Submitted';
$timenow = date('-Y-m-d-H-i-s');
$model->jha = UploadedFile::getInstance($model,'jha');
if (!empty($model->jha)) {
$model->jha->saveAs('uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension);
//save the path in the db
$model->wp_jhaattach = 'uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension;
}
$model->jha = null;
$model->save(false);
return $this->redirect(['availablework']);
}
else{
return $this->renderAjax('createnewworkbasic', [
'model' => $model,
]);
}
}
Action Update
public function actionUpdatenewwork($id)
{
$anotherchecklistitems = Anotherclreq::find()->select('acl_clname')->where(['acl_wpno'=>$id])->column();
$anotherpermitlistitems = Anotherpermitreq::find()->select('apr_apname')->where(['apr_wpno'=>$id])->column();
$model = $this->findModel($id);
//we have a relation between workpermit and anotherchecklist named anotherchecklistrel
$modelsAnotherchecklist = $model->anotherchecklistrel;
$modelsAnotherpermitlist = $model->anotherpermitlistrel;
if(isset($_POST['Workpermit']['anotherchecklist'])){
$oldIDs = ArrayHelper::map($modelsAnotherchecklist, 'acl_id', 'acl_id');
$oldIDstring = implode(",", $oldIDs);
// print_r($oldIDstring);
// die();
foreach ($oldIDs as $id) {
Anotherclreq::findOne($id)->delete();
}
//die();
$anotherChecklist = $_POST['Workpermit']['anotherchecklist'];
foreach ($anotherChecklist as $value) {
$anotherclreq = new Anotherclreq();
$anotherclreq->acl_wpno = $model->wp_no;
$anotherclreq->acl_clname = $value;
$anotherclreq->save();
}
}
if(isset($_POST['Workpermit']['anotherpermittype'])){
$oldAPs = ArrayHelper::map($modelsAnotherpermitlist, 'apr_id', 'apr_id');
$oldAPstring = implode(",", $oldAPs);
// print_r($oldIDstring);
// die();
foreach ($oldAPs as $id) {
Anotherpermitreq::findOne($id)->delete();
}
$anotherPermit = $_POST['Workpermit']['anotherpermittype'];
foreach ($anotherPermit as $value) {
$anotherpermitreq = new Anotherpermitreq();
$anotherpermitreq->apr_wpno = $model->wp_no;
$anotherpermitreq->apr_apname = $value;
$anotherpermitreq->save();
}
}
if(Yii::$app->request->post('submit')==='tello'){
var_dump("Save is clicked");
die();
}
elseif(Yii::$app->request->post('submit')==='hello'){
var_dump("Submit is clicked");
die();
}
if ($model->load(Yii::$app->request->post())) {
//$model->wp_nwopcheckliststatus = 'Submitted';
$model->save();
return $this->redirect(['viewall', 'id' => $model->wp_no]);
}
return $this->render('updatenewwork', [
'model' => $model,
'anotherchecklistitems' => $anotherchecklistitems,
'anotherpermitlistitems' => $anotherpermitlistitems,
]);
}
In the create form it works good. But for the update form it doesn't. Please help.
Some Observation -
I've changed the buttons like below -
<?= Html::submitButton('Save',['id' => 'savename','name'=>'savename', 'value' => 'savename','class' => 'btn btn-primary']) ?>
<?= Html::submitButton('Save & Submit',['id' => 'submitname','name'=>'submitname', 'value' => 'submitname','class' => 'btn btn-success']) ?>
Now If I use the following code in Controller action, the form is submitting as it should -
if (Yii::$app->request->isPost) {
if ($model->load(Yii::$app->request->post())) {
$model->wp_nwopcheckliststatus = 'Saved';
$model->save();
return $this->redirect(['viewall', 'id' => $model->wp_no]);
}
}
But as soon as I change $model->load(Yii::$app->request->post()) to $model->load(Yii::$app->request->post('savename')) it stops working.
If I were you, I would create a hidden text field.
and instead of directly submitting the form, I would have attached an event listener.
meaning by javascript, add on click event on the buttons and change the value of hidden text field to anything - 0 - 1 or anything. and then submit the form.
for example:
<input type="hidden" name="pressed" id="pressed" />
<script>
$('#save').click(function(){
$('pressed').val("save");
});
$('#save-and-submit').click(function(){
$('pressed').val("submit");
});
</script>
then check in $_POST['pressed'];

captcha not working using scenarios in yii2

I am trying to add captcha validation based on scenario, for which I am first retrieving number of failed attempts from database. For which I am using checkattempts() function. Based on the result I am displaying captcha in view and adding scenario condition in controller as below.
In LoginForm model:
public function rules()
{
return [
[['username', 'password'], 'required', 'on'=>'loginpage'],
[['username', 'password'], 'required', 'on'=>'withCaptcha'],
[['reference_url'], 'safe'],
[['verifyCode'], 'captcha', 'skipOnEmpty' => true,'on'=>'withCaptcha'],
['username','email', 'on'=>'loginpage', 'message'=> 'Please enter a valid email address'],
['password', 'validatePassword', 'on'=>'loginpage'],
['password', 'validatePassword', 'on'=>'withCaptcha'],
];
}
public function checkattempts($uname)
{
$user = \frontend\models\User::findByEmail($uname);
$ip = $this->get_client_ip();
if($user){
$data = (new Query())->select('*')
->from('login_attempts')
->where(['ip' => $ip])->andWhere(['user_ref_id' => $user->id])
->one();
if($data["attempts"] >=3){
return true;
}else{
return false;
}
}
return false;
}
in SiteController.php controller
public function actionLogin() {
if (!\Yii::$app->user->isGuest) {
return $this->redirect(Yii::$app->getUrlManager()->getBaseUrl() . '/../../');
}
$model = new \common\models\LoginForm();
$model->scenario = 'loginpage';
$captcha = false;
if(Yii::$app->request->post()){
$post_variables =Yii::$app->request->post('LoginForm');
if ($model->checkattempts($post_variables['username'])) {
$model->scenario = 'withCaptcha';
$captcha = true;
}
}
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->login(); print_r($model->getErrors()); exit;
} else {
return $this->render('login', [
'model' => $model, 'captcha' => $captcha,
]);
}
In my login.php view:
<?php if($captcha) { ?>
<?= $form->field($model, 'verifyCode')->widget(Captcha::className(),
['template' => '<div class="captcha_img">{image}</div>'
. '<a class="refreshcaptcha" href="#">'
. Html::img('/images/imageName.png',[]).'</a>'
. 'Verification Code{input}',
])->label(FALSE); ?>
<?php } ?>
In my controller when I am tring to print model errors at $model->login() function it is giving below error everytime even though the verification code is correct.
Array ( [verifycode] => Array ( [0] => The verification code is incorrect. ) )
Why is it failing every time. Is there any mistake in the code written?
Thanks in advance

yii2 file upload error- Call to a member function saveAs() on null

I've learned a little bit about yii2 framework, but I've got an error which I can't solve. I'm trying to add a image to signup form.
view:
<?php $form = ActiveForm::begin(['id' => 'form-signup', 'options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'voornaam')->textInput(['autofocus' => true]) ?>
<?= $form->field($model, 'bedrijf') ?>
<?= $form->field($model, 'telefoon') ?>
<?= $form->field($model, 'username')?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'file')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
controller
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
model:
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new User();
$imageName = $user->username;
$user->file = UploadedFile::getInstance($user,'file');
$user->file->saveAs( 'uploads/'.$imageName.'.'.$model->file->extension );
$user->picture = 'uploads/'.$imageName.'.'.$model->file->extension;
$user->voornaam = $this->voornaam;
$user->bedrijf = $this->bedrijf;
$user->telefoon = $this->telefoon;
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
return $user->save() ? $user : null;
}
I'm getting the error:
Call to a member function saveAs() on null
What did I do wrong?
(I'm using the advanced template).
you should use $this instead of $user or you should add
$user=$this
because simply $user is new instance and it's field are empty !
It looks like you are mentioning wrong file path, you must mention rootpath for save function
for example
$user->file->saveAs(\Yii::getAlias('#webroot').'/uploads/'.$imageName.'.'.$model->file->extension );
I used separate upload function to upload a file and it's worked.
my view
<?php $form = ActiveForm::begin(['id' => 'form-signup','options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, "files")->fileInput() ?>
<div class="form-group">
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
controller
public function actionSignup() {
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
$model->files = \yii\web\UploadedFile::getInstance($model,'files');
if ($model->upload() && $user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
and my model is
//declare variable
public $files;
//add this to your rules
[['files'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, jpeg']
//File upload function
public function upload()
{
if ($this->validate()) {
$this->files->saveAs('../web/uploads/' . $this->files->baseName. '.' .$this->files->extension);
$this->picture = '../web/uploads/' . $this->files->baseName. '.' .$this->files->extension;
return true;
} else {
return false;
}
}
public function signup()
{
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->picture = $this->picture;
$user->setPassword($this->password);
$user->generateAuthKey();
if ($user->save()) {
return $user;
}
else{
return null;
}
}
Just sharing you my solution, change the path to uploads folder to ../uploads/
In your model try changing saveAs function as shown below
$user->file->saveAs( '../uploads/'.$imageName.'.'.$model->file->extension );
I am a beginner in yii2, I faced a problem when i tried the file upload code from
https://www.yiiframework.com/doc/guide/2.0/en/input-file-upload,
this solved my problem

Yii2 Post to controller and get back data

This is my code in view.
<?= $form->field($model, 'projectTitle')->dropDownList($fullprojectlist, [
'prompt'=>'-Choose a Course-',
'id' => 'projectList',
'type'=> 'POST',
'onchange'=>' var value = $("#projectList :selected").val();
//$("#draftproposalform-supervisor").val(value);'
$.post("'.Yii::$app->urlManager->createUrl(["/draftproposalform.php", "id" => value).'", function(data) {
//set value for text box
}
]);?>
<?= $form->field($model, 'supervisor')->textInput(['readonly'=> 'true']); ?>
I am trying to pass the selected value to the controller so that I can query the database to look for the relevant information. Then send back that information to the view to settext.
I know how to get data from the database. I just don't know how I can pass the selected value to controller and get back a value to settext while maintaining the selected value in view.
public function actionDraftproposalform() {
$model = new DraftProposalForm();
if($model->load(Yii::$app->request->post()) && $model->validate())
{
return $this->refresh();
}
else {
$query = new Query;
$query->select(['User.name', 'Project.title', 'Project.project_ID'])
->from('Project')
->innerJoin('Supervisor', '`Project`.`supervisor_ID` = `Supervisor`.`supervisor_ID`')
->innerJoin('User', '`Supervisor`.`user_ID` = `User`.`user_ID`')
->where(['Project.project_type_ID'=>1, 'Project.approval_ID'=>2]);
$projectlist = $query->all();
$fullprojectlist = ArrayHelper::map($projectlist, 'name', 'title', 'project_ID');
return $this->render('draftproposalform', [
'model'=>$model,
'fullprojectlist' => $fullprojectlist]);
}
}
Sorry if it's messy. Truthfully, I don't even know if passing the data back to here is the correct choice.
Edited Codes
View
<?php
$this->registerJs(' $("#projectList").change(function() {
var value = $("#projectList option:selected").val();
alert(value);
$.post(
"'.Yii::$app->urlManager->createUrl(["/draftproposalform.php"]).'",
{id:value},
function(data) {
alert("Test");
$("input[name=\'supervisor\']").val(data);
}); });');
?>
<?= $form->field($model, 'projectTitle')->dropDownList($projectlist, [
'prompt'=>'-Choose a Course-',
'id' => 'projectList',
'type'=> 'POST'
]);
?>
<?= $form->field($model, 'supervisor')->textInput(['readonly'=> 'true']); ?>
Controller
public function actionDraftproposalform() {
$model = new DraftProposalForm();
if(Yii::$app->request->isPost)
{
$id = Yii::$app->request->post("id");
$super = DbProject::findOne(["project_ID"=>$id]);
$supervisor = DbSupervisor::findOne(["supervisor_ID"=>$super->supervisor_ID]);
$user = DbUser::findOne(["user_ID"=>$supervisor->user_ID]);
//$super = DbSupervisor::findOne(["supervisor_ID"=>$id]);
echo $user->name;
exit;
}
else {
$projectlist = ArrayHelper::map(DbProject::find()->where(['project_type_ID' => 1, 'approval_ID' => 2])->asArray()->all(), 'project_ID', 'title');
return $this->render('draftproposalform', [
'model'=>$model,
'projectlist' => $projectlist]);
}
}
Can you test this.
//Controller
<?
public function actionDraftproposalform() {
$model = new DraftProposalForm();
if(Yii::$app->request->isPost)
{
$id=Yii::$app->request->post("id");
$super=Supervisor::findOne(["supervisor_ID"=>$id]);
if($super) echo $super->name;else echo "Not found";exit;
}
else {
$query = new Query;
$query->select(['User.name', 'Project.title', 'Project.project_ID'])
->from('Project')
->innerJoin('Supervisor', '`Project`.`supervisor_ID` = `Supervisor`.`supervisor_ID`')
->innerJoin('User', '`Supervisor`.`user_ID` = `User`.`user_ID`')
->where(['Project.project_type_ID'=>1, 'Project.approval_ID'=>2]);
$projectlist = $query->all();
$fullprojectlist = ArrayHelper::map($projectlist, 'name', 'title', 'project_ID');
return $this->render('draftproposalform', [
'model'=>$model,
'fullprojectlist' => $fullprojectlist]);
}
}
//view register js: put this in your view
<?
$this->registerJs(' $("#projectList").change(function(){
var value = $("#projectList option:selected").val();
$.post(
"'.Yii::$app->urlManager->createUrl(["/draftproposalform"]).'",
{ id:value },
function(data) {
$( "#draftproposalform-supervisor").val(data);
}); });');
?>

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;