I need you to change the PRODUCT field (dropdownlist) is changed the MIN and MAX properties kartik\SLIDER component
---- form ----
<?=
$form->field($model, 'product_id', [
'inputOptions' => [
'class' => 'selectpicker '
]
]
)->dropDownList(app\models\Product::getHierarchy(), ['prompt' => 'Selecione', 'class'=>'form-control required']);
?>
use kartik\slider\Slider;
echo $form->field($model, 'commission_percent')->widget(Slider::classname(), [
'name'=>'commission_percent',
'value'=>7,
'sliderColor'=>Slider::TYPE_GREY,
'handleColor'=>Slider::TYPE_SUCCESS,
'pluginOptions'=>[
'handle'=>'round',
'tooltip'=>'always',
'min'=>10,
'max'=>50,
'step'=>1,
]
]);
---- rules ----
['commission_percent', 'number','min'=>30,'max'=>40, 'when' => function($model) {
return $model->product_id == 14;
}],
EDITED
Each product has a max value and minimum commission amount. I do not know how to catch these values and transfer to the properties max and min of SLIDER.
EDITED 2
My controller actionListx return:
Invalid Parameter – yii\base\InvalidParamException
Response content must not be an array.
My _form:
<?php
$productId = Html::getInputId($model, 'product_id');
$comissionId = Html::getInputId($model, 'commission_percent');
$url = \Yii::$app->getUrlManager()->createUrl('/dailyproductivity/listx');
$js = <<<JS
$('#{$productId}').on('change', function () {
var form = $('#dailyproductivity-form');
$.ajax({
url: '{$url}',
type: 'post',
data: form.serialize(),
success: function(data) {
var min = data.min;
var max = data.max;
$("#{$comissionId}").data('slider').options.min = min;
$("#{$comissionId}").data('slider').options.max = max;
$("#{$comissionId}").slider('setValue', min);
}
});
});
JS;
$this->registerJs($js);
?>
My ProductivityController:
public function actionListx()
{
$model = new Dailyproductivity();
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
$product = Product::findOne($model->product_id);
if ($product !== null) {
return [
'min' => $product->min_value,
'max' => $product->max_value,
];
}
}
return [
'min' => '0',
'max' => '100'
];
}
Print
If you are not saving this min and max values and the correspond ids somewhere in your db (and i think you should), you can do that with pure js. Here is a example:
<?php
$productId = Html::getInputId($model, 'product_id');
$comissionId = Html::getInputId($model, 'commission_percent');
$js = <<<JS
$('#{$productId}').on('change', function () {
var id = $(this).val();
if (id == 14) {
var min = 30;
var max = 40;
} else {
var min = 0;
var max = 100;
}
$("#{$comissionId}").data('slider').options.min = min;
$("#{$comissionId}").data('slider').options.max = max;
$("#{$comissionId}").slider('setValue', min);
});
JS;
$this->registerJs($js);
And make sure to add the new rule in your model:
public function rules()
{
return [
// the other rules
// ...
['commission_percent', 'number','min'=>0,'max'=>100] // the general values
['commission_percent', 'validate']
];
}
/**
* #param string $attribute
*/
public function validate($attribute)
{
if ($this->product_id == 14) {
$min = 30;
$max = 40;
if ($this->attribute < $min || $this->attribute > $max) {
$this->addError($attribute, 'error message'));
}
}
}
But if you have a lot of products and each one have a specific value of min and max, instead of creating a bunch of if statements, you can create a new action that checks the model that have this two values (min and max) saved and return them. And you can access it with a ajax call.
Here is a example of this ajax (assuming you added the min_value and max_value attributes in your Product model:
in your view:
$productId = Html::getInputId($model, 'product_id');
$comissionId = Html::getInputId($model, 'commission_percent');
$url = Url::to(['controller/action-with-ajax']);
$js = <<<JS
$('#{$productId}').on('change', function () {
var form = $('#my-form-id');
$.ajax({
url: '{$url}',
type: 'post',
data: form.serialize(),
success: function(data) {
var min = data.min;
var max = data.max;
$("#{$comissionId}").data('slider').options.min = min;
$("#{$comissionId}").data('slider').options.max = max;
$("#{$comissionId}").slider('setValue', min);
}
});
});
JS;
$this->registerJs($js);
And your controller:
public function actionWithAjax()
{
$model = new Model(); // the model you are using in this form
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
if ($product = Product::findOne($model->product_id)) !== null) {
return [
'min' => $product->min_value,
'max' => $product->max_value,
];
}
}
return [
'min' => '0',
'max' => '100'
];
}
Related
i had a problem on my RESTAPI. i'm working with backend that makes the API, but i can't post data to the server. due to the error that appears on my debug console. here's the REST-API end-point source code.
`
class PeminjamanController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$data = Peminjaman::all();
return response()->json(['Data User : ', PeminjamanResource::collection($data) ], Response::HTTP_OK);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create($id)
{
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request, $id)
{
try {
//code...
$data = Request()->all();
if( $id == 1) {
$validator = Validator::make($request->all(),[
'dosen_id' => 'required',
'matkul_id' => 'required',
'spo_id' => 'required'
],[
'dosen_id.required' =>'Dosen Tidak Boleh Kosong',
'matkul_id.required' =>'Mata kuliah Tidak Boleh Kosong',
'spo_id.required' =>'Tindakan Tidak Boleh Kosong',
]);
if($validator->fails()){
return response()->json($validator->errors(),
Response::HTTP_UNPROCESSABLE_ENTITY);
}
$pinjam = new Permintaan();
$pinjam->id = Uuid::uuid4()->getHex();
$pinjam->kd_permintaan = $data['kd_peminjaman'];
$pinjam->user_id = Auth::user()->id;
$pinjam->dosen_id = $data['dosen_id'];
$pinjam->matkul_id = $data['matkul_id'];
$pinjam->spo_id = $data['spo_id'];
$pinjam->tgl_minta = Carbon::now();
$pinjam->diserahkan = NULL;
$pinjam->aprovals = "Belum";
$pinjam->status = "Menunggu Persetujuan";
// $pinjam->keterangan = NULL;
$pinjam->save();
foreach($request->barang_id as $key => $barang){
$stok = Barang::findOrFail($barang);
if ($request->jumlah[$key] > $stok->stok) {
return response('[200] - Maaf Stok Barang Melewati Batas');
}else{
DetailPinjam::create([
'id' => Uuid::uuid4()->getHex(),
'permintaan_id' => $pinjam->id,
'kondisi_id' => 2,
'barang_id' => $barang,
'jumlah' =>$request->jumlah[$key],
'fix_jumlah_kembali' =>$request->jumlah[$key],
]);
$stokpinjam = $stok->stok - $request->jumlah[$key];
$stok->update([
'stok' => $stokpinjam,
]);
$response = [
'success' => true,
'message' => 'Peminjaman Created',
'data' => $pinjam
];
return response()->json($response, Response::HTTP_CREATED);
}
}
}elseif ($id == 2 ){
Request()->validate([
'dosen_id' => 'required',
'matkul_id' => 'required',
'spo_id' => 'required',
'tgl_kembali' => 'required',
],[
'dosen_id.required' =>'Dosen Tidak Boleh Kosong',
'matkul_id.required' =>'Mata kuliah Tidak Boleh Kosong',
'spo_id.required' =>'Tindakan Tidak Boleh Kosong',
'tgl_kembali.required' =>'Tanggal Pengembalian Tidak Boleh Kosong',
]);
$data = Request()->all();
$pinjam = new peminjaman();
$pinjam->id = Uuid::uuid4()->getHex();
$pinjam->kd_peminjaman = $data['kd_peminjaman'];
$pinjam->user_id = Auth::user()->id;
$pinjam->dosen_id = $data['dosen_id'];
$pinjam->matkul_id = $data['matkul_id'];
$pinjam->spo_id = $data['spo_id'];
$pinjam->tgl_pinjam = Carbon::now();
$pinjam->tgl_kembali = $data['tgl_kembali'];
$pinjam->diserahkan = NULL;
$pinjam->aprovals = "Belum";
$pinjam->status = "Menunggu Persetujuan";
$pinjam->keterangan = NULL;
$pinjam->save();
foreach($request->barang_id as $key => $barang){
$stok = Barang::findOrFail($barang);
if ($request->jumlah[$key] > $stok->stok) {
return response('[200] - Maaf Stok Barang Melewati Batas');
}else{
DetailPinjam::create([
'id' => Uuid::uuid4()->getHex(),
'peminjaman_id' => $pinjam->id,
'barang_id' => $barang,
'jumlah' => $request->jumlah[$key]
]);
$stokpinjam = $stok->stok - $request->jumlah[$key];
$stok->update([
'stok' => $stokpinjam,
]);
$response = [
'success' => true,
'message' => 'Peminjaman Created',
'data' => $pinjam
];
return response()->json($response, Response::HTTP_CREATED);
}
}
}
} catch (QueryException $e) {
//throw $th;
return response()->json([
'message' => "Failed" . $e->errorInfo
]);
}
}
`
and here the dart dio push method.
`
Kirim() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
var token = localStorage.getString('access_token');
try {
var data = FormData.fromMap({
'kd_peminjaman': kodepruduct,
'user_id': id_pengguna,
'dosen_id': dosendrop,
'matkul_id': matakuliahdrop,
'spo_id': spodrop,
//'tgl_minta': '${tanggal.day}.${tanggal.month}.${tanggal.year}',
'tgl_kembali':
'${tanggalkembali.day}.${tanggalkembali.month}.${tanggalkembali.year}',
'[barang_id][]': {
[id]
},
'[jumlah[]]': {
[jumlah]
},
});
var dio = Dio();
dio.options.headers['Authorization'] = 'Bearer $token';
//dio.options.headers['Content-Type'] = 'multipart/form-data';
dio.options.headers['Accept'] = 'application/json';
dio.options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
var response = await dio
.post('http://silk.polindra.ac.id/api/peminjaman/2', data: data);
print(response.statusMessage);
} catch (e) {
print(e);
}
}
`
and i got response from the rest-api method like this.
i have tried to change the atribute on the FormData. on the array
barang[]: [id], jumlah[]: [jumlah]
to jsonEncode method
barang[]: jsonEncode([id]), jumlah[]: jsonEncode([jumlah])
and these too
[barang[]]: [id]], [jumlah[]: [jumlah]]
and the last
barang[]: {[id]}, jumlah[]: {[jumlah]}
all of refactoring atrribut i made, doesn't give any effect, all of method give the same error message
can some one help me.. plz...
sorry for my bad english.. i'm not usually spoken english in my country.
actually, the reason you get this issue is related to your API code on line 164 it suppose to string but it's returning an array. to check which parameter making an issue you can simply diedump by
dd($request->all());
and test it from the postman
I'm trying to get a featured-image from my custom taxonomy-*projects* term-*elfla*.
I managed to get a image from the posts with this code what i found here but I don't understand how to do it with taxonomy terms.
At this point I do not understand how to get the featured image source and whether the 'GET' request url is correct.
JS:
var portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET','http://localhost/test/wordpress/wp-json/wp/v2/posts/?filter=projects&filter=elfla&_embed');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
createHTML(data);
portfolioPostsBtn.remove();
console.log(data);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
});
}
function createHTML(postsData) {
var ourHTMLString = '';
for (i = 0; i < postsData.length; i++) {
ourHTMLString += '<img src="'+postsData[i].featured_image_thumbnail_url+ '" alt="img">';
}
portfolioPostsContainer.innerHTML = ourHTMLString;
}
Functions.php
function my_rest_prepare_post( $data, $post, $request ) {
$_data = $data->data;
$thumbnail_id = get_term_meta( $post->ID , 'thumbnlai' false );
$thumbnail = wp_get_attachment_image_src( $thumbnail_id );
$_data['featured_image_thumbnail_url'] = $thumbnail[0];
$data->data = $_data;
return $data;
}
add_filter( 'rest_prepare_post', 'my_rest_prepare_post', 10, 3 );
Use this function.
**function custom_api_get_all_posts() {
register_rest_route( 'custom/v1', '/all-posts', array(
'methods' => 'GET',
'callback' => 'custom_api_get_all_posts_callback'
)); }
function custom_api_get_all_posts_callback( $request ) {
// Initialize the array that will receive the posts' data.
$posts_data = array();
// Receive and set the page parameter from the $request for pagination purposes
$paged = $request->get_param( 'page' );
$paged = ( isset( $paged ) || ! ( empty( $paged ) ) ) ? $paged : 1;
// Get the posts using the 'post' and 'news' post types
$posts = get_posts( array(
'paged' => $paged,
'post__not_in' => get_option( 'sticky_posts' ),
'posts_per_page' => 1000,
'post_type' => array('post') // This is the line that allows to fetch multiple post types.
)
);
// Loop through the posts and push the desired data to the array we've initialized earlier in the form of an object
foreach( $posts as $post ) {
$id = $post->ID;
$post_thumbnail = ( has_post_thumbnail( $id ) ) ? get_the_post_thumbnail_url( $id ) : null;
$posts_data[] = (object) array(
'id' => $id,
'slug' => $post->post_name,
'type' => $post->post_type,
'title' => $post->post_title,
"content" => apply_filters('the_content', $post->post_content),
'featured_img_src' => $post_thumbnail
);
}
return $posts_data; }
use this link http://yourdomin.com/wp-json/custom/v1/all-posts.
I think it will work for you
I've a query to get mrp*rate from table productbatch upto 2 decimal point.
I've tried the following query Productbatch::find()->select('mrp, rate, round((mrp*rate),2) as rateval')->asArray()->one();
When I use only mrp*rate it gives the result but there's 6 or 7 digits after decimal. Please let me know how can I get the result upto 2 decimal points.
example
If I don't use round and if mrp = 32 and rate = 24.64, the result of mrp*rate it gives - 788.47998046875..
If I use Round as shown in the code it doesn't give the result.
What I want is - 788.48.
Productbatch Model
<?php
namespace frontend\modules\invoice\models;
use Yii;
/**
* This is the model class for table "productbatch".
*
* #property integer $itemid
* #property string $productname
* #property string $batchno
* #property string $mfgdate
* #property string $expdate
* #property double $mrp
* #property double $rate
*
* #property Productnames $productname0
*/
class Productbatch extends \yii\db\ActiveRecord
{
public $rateval;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'productbatch';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['batchno'], 'string'],
[['mfgdate', 'expdate'], 'safe'],
[['mrp', 'rate'], 'number'],
[['productname'], 'string', 'max' => 25],
[['productname'], 'exist', 'skipOnError' => true, 'targetClass' => Productnames::className(), 'targetAttribute' => ['productname' => 'productnames_productname']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'itemid' => 'Itemid',
'productname' => 'Productname',
'batchno' => 'Batchno',
'mfgdate' => 'Mfgdate',
'expdate' => 'Expdate',
'mrp' => 'Mrp',
'rate' => 'Rate',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getProductname0()
{
return $this->hasOne(Productnames::className(), ['productnames_productname' => 'productname']);
}
public static function getBatchNo($cat_id)
{
$out = [];
$data = Productbatch::find()
->where(['productname' => $cat_id])
->orDerBy([
'expdate'=>SORT_DESC,
])
->limit(5)
->asArray()
->all();
foreach ($data as $dat) {
$out[] = ['id' => $dat['batchno'], 'name' => $dat['batchno']];
}
return $output = [
'output' => $out,
'selected' => ''
];
}
public static function getItemdetails($cat_id, $subcat_id)
{
$out = [];
$data = Productbatch::find()
->where(['productname' => $cat_id])
->andWhere(['batchno' => $subcat_id])
->orDerBy([
'expdate'=>SORT_DESC,
])
->limit(5)
->asArray()
->all();
foreach ($data as $dat) {
$out[] = ['id' => $dat['itemid'], 'name' => $dat['itemid']];
}
return $output = [
'output' => $out,
'selected' => ''
];
}
// public static function getItemdetails($cat_id, $subcat_id)
// {
// $out = [];
// $data = Productbatch::find()
// ->where(['productname' => $cat_id])
// ->andWhere(['batchno' => $subcat_id])
// ->orDerBy([
// 'expdate'=>SORT_DESC,
// ])
// ->limit(5)
// ->asArray()
// ->all();
// foreach ($data as $dat) {
// $out[] = ['id' => $dat['itemid'], 'name' => $dat['itemid']];
// }
// return $output = [
// 'output' => $out,
// 'selected' => ''
// ];
// }
}
Controller Action -
public function actionGetForItemid($prodname , $batchno)
{
$item = Productbatch::find()->joinWith(['productname0'])->joinWith(['productname0', 'productname0.hsncode'])->select('max(itemid) as itemid, expdate, mrp,rate, productname, batchno, round(rate*mrp,2) as rateval')->where(['productname'=>$prodname])->andWhere(['batchno'=>$batchno])->asArray()->one();
echo Json::encode($item);
}
Javascript that is calling the controller action -
<?php
/* start getting the itemid */
$script = <<< JS
function getItemID(item) {
var index = item.attr("id").replace(/[^0-9.]/g, "");
var batch = product = 0;
var id = item.attr("id");
var myString = id.split("-").pop();
if (myString == "productname") {
fetch = index.concat("-batchno");
product = item.val();
batch = $("#productsales-"+fetch+"").val();
} else {
fetch = index.concat("-productname");
batch = item.val();
product = $("#productsales-"+fetch+"").val();
}
$.get('index.php?r=invoice/bills/get-for-itemid',{ prodname : product,batchno : batch}, function(data){
alert(data);
var data = $.parseJSON(data);
var getItemid = data;
itemID = "productsales-".concat(index).concat("-itemid");
$("#"+itemID+"").val(getItemid["itemid"]);
expDate = "productsales-".concat(index).concat("-expdate");
$("#"+expDate+"").val(getItemid["expdate"]);
mRP = "productsales-".concat(index).concat("-mrp");
$("#"+mRP+"").val(getItemid["mrp"]);
rATE = "productsales-".concat(index).concat("-rate");
$("#"+rATE+"").val(getItemid["rateval"]);
});
}
JS;
$this->registerJs($script, View::POS_END);
/* end getting the itemid */
?>
Form fields that is being populated -
<?= $form->field($modelsProductsales, "[{$i}]rate")->label(false)->textInput(['maxlength' => true,'class' => 'rate','placeholder' => 'Rate']) ?>
Be sure your Productbatch model has a publica var rateval
class Productbatch extends \yii\db\ActiveRecord
{
public $rateval
...
and then you can refer to the rateval content in you views using
$model->rateval;
OR do the fact you have the result not rounded whet you use mrp*rate
a simple solution could be round in javascript
Math.round(num * 100) / 100
and in your case
$("#"+rATE+"").val( Math.round( getItemid["rateval"]*100)/100 );
I want to handle user registration via ajax call. So therefore I've created a registration class (defined as a service) which will be loaded in different controllers:
public function loadRegisterForm($request)
{
$user = new User();
$form = $this->createForm(RegistrationType::class, $user, array('attr' => array('class' => 'ajaxRegisterForm',)));
$form->handleRequest($request);
$errors = "";
$parametersArray['result'] = "";
if ($form->isSubmitted())
{
if ($form->isValid())
{
$password = $this->get('security.password_encoder')
->encodePassword($user, $user->getPlainPassword());
$user->setPassword($password);
$user->setIsActive(1);
$user->setLastname('none');
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$parametersArray['result'] = new JsonResponse(
array(
'message' => 'Success! User registered!',
'result' => $this->renderView('ImmoBundle::security/successlogin.html.twig')
), 400);
}
else
{
$errors = $this->get('validator')->validate($form);
$parametersArray['result'] = new JsonResponse(
array(
'message' => 'Failure! User not registered!',
'result' => $this->renderView('ImmoBundle::security/successlogin.html.twig'),
'errors' => $errors,
), 200);
}
}
$parametersArray['register_form'] = $form;
$parametersArray['errors'] = $errors;
return $parametersArray;
}
Then I've created a main controller, where registration form is being loaded:
/*
* #Route("/", name="MainPageNotPaginated")
*/
public function indexAction(Request $request)
{
/**
* Load register form
*/
$registerForm = $this->get('register_form_service');
$registerFormParameters = $registerForm->loadRegisterForm($request);
return $this->render(
'ImmoBundle::Pages/mainPage.html.twig',
array(
'register_form' => $registerFormParameters['register_form']->createView(),
'errors' => $registerFormParameters['errors'],
'result' => $registerFormParameters['result'],
)
);
}
Further I've added an ajax call to my javascript file:
$('.registerFormContainer').on('submit', '.ajaxRegisterForm', function (e) {
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize()
})
.done(function (data) {
if (typeof data.message !== 'undefined') {
$('.registerFormContainer').html(data.result);
}
alert('success');
})
.fail(function (jqXHR, textStatus, errorThrown) {
if (typeof jqXHR.responseJSON !== 'undefined') {
$('.registerFormError').html(jqXHR.responseJSON.result);
} else {
alert("fail");
}
});
});
Now, when I submit the registration form without filling in data (which normally should return an error) I've got an 'success' alert. The same 'success' alert is visible when the submitted registration form is valid.
I've tried
console.log(data.message)
but console says 'undefined'.
What am I doing wrong here?
Ok, I've figured it out. I've just added this line to my main controller (not the service one):
if ( $request->isXmlHttpRequest() ) {
return $registerFormParameters['result'];
}
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);
}); });');
?>