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'];
Related
Here i can only able preview the images on update the model. I want to load the images properly so user can remove one r more file and update will work accordingly Here is my controller
public function actionUpdate($id)
{
$model = $this->findModel($id);
$session_data = \common\models\Customer::find()->where(['user_id' => $model->customer_user_id])->one();
$towing = \common\models\TowingRequest::find()->where(['id' => $model->towing_request_id])->one();
$images_old = \common\models\Images::find()->where(['=', 'vehicle_id', $model->id])->all();
$images = \common\models\Images::find()->where(['=', 'vehicle_id', $model->id])->one();
if (!$images) {
$images = new \common\models\Images();
}
if ($images_old) {
foreach ($images_old as $image) {
$baseurl = \Yii::$app->request->BaseUrl;
$image_url = $baseurl . '../backend/uploads/' . $image->thumbnail;
$all_images[] = Html::img("$image_url", ['class' => 'file-preview-image']);
}
} else {
$all_images = '';
}
$vehiclefeatures = new \common\models\VehicleFeatures();
$vehiclecondition = new \common\models\VehicleCondition();
$featuredata = \common\models\VehicleFeatures::find()->where(['=', 'vehicle_id', $model->id])->all();
$conditiondata = \common\models\VehicleCondition::find()->where(['=', 'vehicle_id', $model->id])->all();
$features = \common\models\Features::find()->all();
// $vf = Yii::$app->db->createCommand('SELECT * FROM features f left join vehicle_features vf on vf.features_id=f.id;')->queryAll();
$condition = \common\models\Condition::find()->all();
if ($model->load(Yii::$app->request->post()) && $towing->load(Yii::$app->request->post()) && $vehiclefeatures->load(Yii::$app->request->post()) && $vehiclecondition->load(Yii::$app->request->post()) && $images->load(Yii::$app->request->post())) {
$towing->save();
if (!$model->save()) {
$result = [];
// The code below comes from ActiveForm::validate(). We do not need to validate the model
// again, as it was already validated by save(). Just collect the messages.
foreach ($model->getErrors() as $attribute => $errors) {
$result[Html::getInputId($model, $attribute)] = $errors;
}
return $this->asJson(['validation' => $result]);
// Yii::$app->response->statusCode = 422;
}
//delet vehicle features and add new features
$command = Yii::$app->db->createCommand()
->delete('vehicle_features', 'vehicle_id = ' . $model->id)
->execute();
if ($vehiclefeatures->value) {
$vehicle_feature = \common\models\VehicleFeatures::inert_vehicle_feature($model, $vehiclefeatures->value);
}
//delete vehicle condition and add new features
$command = Yii::$app->db->createCommand()
->delete('vehicle_condition', 'vehicle_id = ' . $model->id)
->execute();
if ($vehiclecondition->value) {
$vehicle_condition = \common\models\VehicleCondition::inert_vehicle_condition($model, $vehiclecondition->value);
}
$photo = UploadedFile::getInstances($images, 'name');
if ($photo) {
$command = Yii::$app->db->createCommand()
->delete('images', 'vehicle_id = ' . $model->id)
->execute();
$save_images = \common\models\Images::save_container_images($model->id, $photo);
}
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
'towing' => $towing,
'images' => $images,
'features' => $features,
'condition' => $condition,
'vehiclefeatures' => $vehiclefeatures,
'vehiclecondition' => $vehiclecondition,
'all_images' => $all_images,
'featuredata' => $featuredata,
'conditiondata' => $conditiondata,
'session_data' => $session_data,
]);
}
And here is my form where I have an issue on update the images. I know here I am just previewing the image by adding it in $all_images[] in the controller and initialPreview => $all_images in form to just show it on upload. Now I want exactly is to load the images properly so I can remove any image and can able to add more images. I just want here is how to load all the images properly in the upload widget on update After uploading it properly on update i can process it on the controller that i will delete and unlink all images and uploading the updating files
Here is my form with model images
<?=
$form->field($images, 'name[]')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*', 'multiple' => true],
'pluginOptions' => [
'previewFileType' => 'image',
'allowedFileExtensions' => ['jpg', 'gif', 'png', 'bmp','jpeg'],
'showUpload' => true,
'initialPreview' => $all_images,
'overwriteInitial' => true,
],
]);
?>
Yii2 Fileinput Upload Multiple Images, AJAX based Images Previews and Delete Images.
Please Refer For Multiple Images : https://stackoverflow.com/a/53832224/2218492
Table : products_images
id (Primary)
product_id (FK)
image
Table : product
id (Primary)
Name
ect
Here View Forms...
<?php
use yii\helpers\Html;
use yii\helpers\Url;
use kartik\widgets\FileInput;
?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?php echo '<label class="control-label">Choose an Image file(.png, .jpg)</label>'; ?>
<?php
//For Update Form : Fetch Uploaded Images and create Array to preview
$imagesList = array();
$imagesListId = array();
foreach ($model->productsImages as $img) {
$imagesList[] = Url::base(TRUE) . '/' . $img->image;
$imagesListId[]['key'] = $img->id;
}
?>
<?php
$empty_image = Url::base(TRUE) . "/uploads/image-upload-empty.png";
echo FileInput::widget([
'model' => $model,
'attribute' => 'products_image[]',
'name' => 'products_image[]',
'options' => ['multiple' => true, 'accept' => 'image/*', 'id' => 'products_image_id'],
'pluginOptions' => [
'initialPreview' => $imagesList,
'initialPreviewConfig' => $imagesListId,
'deleteUrl' => Url::to(['products/delete-image']),
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'browseClass' => 'btn btn-primary col-lg-6 col-md-8 col-sm-8 col-xs-6',
'browseIcon' => '<i class="glyphicon glyphicon-plus-sign"></i> ',
'browseLabel' => 'Upload Image',
'allowedFileExtensions' => ['jpg', 'png'],
'previewFileType' => ['jpg', 'png'],
'initialPreviewAsData' => true,
'overwriteInitial' => false,
"uploadUrl" => Url::to(['products/upload']),
'uploadExtraData' => ['products_id' => $model->id, 'is_post' => $model->isNewRecord ? 'new' : 'update'],
'msgUploadBegin' => Yii::t('app', 'Please wait, system is uploading the files'),
//'msgUploadThreshold' => Yii::t('app', 'Please wait, system is uploading the files'),
//'msgUploadEnd' => Yii::t('app', 'Done'),
'msgFilesTooMany' => 'Maximum 15 products Images are allowed to be uploaded.',
'dropZoneClickTitle' => '',
"uploadAsync" => true,
"browseOnZoneClick" => true,
"dropZoneTitle" => '<img src=' . $empty_image . ' />',
'fileActionSettings' => [
'showZoom' => true,
'showRemove' => true,
'showUpload' => false,
],
'validateInitialCount' => true,
'maxFileCount' => 15,
'maxFileSize' => 5120, //5mb
'msgPlaceholder' => 'Select attachments',
],
'pluginEvents' => [
'filebatchselected' => 'function(event, files) {
$(this).fileinput("upload");
}',
/* 'uploadExtraData' => 'function() {
var out = {}, key, i = 0;
$(".kv-input:visible").each(function() {
$el = $(this);
key = $el.hasClass("kv-new") ? "new_" + i : "init_" + i;
out[key] = $el.val();
i++;
});
return out;
}', */
'filepredelete' => 'function(event, files) {
//var abort = true;
var index = uploaded_images.indexOf(files);
if (index !== -1) uploaded_images.splice(index, 1);
console.log(uploaded_images);
$("#productsmaster-images_array").val(uploaded_images);
//return abort;
}',
'fileuploaded' => 'function(event, data, previewId, index){
//alert( data.response.initialPreviewConfig[0].key);
uploaded_images.push(data.response.initialPreviewConfig[0].key);
console.log(uploaded_images);
$("#productsmaster-images_array").val(uploaded_images);
}',
/* 'filepreupload' => 'function(event, data, previewId, index){
var form = data.form, files = data.files, extra = data.extra,
response = data.response, reader = data.reader;
console.log(data.jqXHR);
console.log("File pre upload triggered");
}', */
],
]);
?>
<?= $form->field($model, 'images_array')->hiddenInput()->label(false) ?>
<?php echo '<br>' ?>
<?= Html::submitButton('<i class="glyphicon glyphicon-save-file"></i> UPLOAD FILE', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary'], ['students/create']) ?>
<?php ActiveForm::end(); ?>
<?php
$script = <<< JS
// initialize array
var uploaded_images = [];
JS;
$this->registerJs($script);
?>
Here Controller file:
<?php
/*
* Post products Images Upload Action Via FileInput Yii2 Extention.
*/
public function actionUpload() {
$files = array();
$allwoedFiles = ['jpg', 'png'];
if ($_POST['is_post'] == 'update') {
$products_id = $_POST['products_id'];
if ($_FILES) {
$tmpname = $_FILES['ProductsMaster']['tmp_name']['products_image'][0];
$fname = $_FILES['ProductsMaster']['name']['products_image'][0];
//Get the temp file path
$tmpFilePath = $tmpname;
//Make sure we have a filepath
if ($tmpFilePath != "") {
//save the filename
$shortname = $fname;
$size = $_FILES['ProductsMaster']['size']['products_image'][0];
$ext = substr(strrchr($shortname, '.'), 1);
if (in_array($ext, $allwoedFiles)) {
//save the url and the file
$newFileName = Yii::$app->security->generateRandomString(40) . "." . $ext;
//Upload the file into the temp dir
if (move_uploaded_file($tmpFilePath, 'uploads/products/' . $newFileName)) {
$productsImages = new productsImages();
$productsImages->products_id = $products_id;
$productsImages->image_for = 'products';
$productsImages->image = 'uploads/products/' . $newFileName;
$productsImages->created_at = time();
$productsImages->save();
$files['initialPreview'] = Url::base(TRUE) . '/uploads/products/' . $newFileName;
$files['initialPreviewAsData'] = true;
$files['initialPreviewConfig'][]['key'] = $productsImages->id;
return json_encode($files);
}
}
}
} /* else {
return json_encode(['error' => 'No files found for pload.']);
} */
return json_encode($files);
} else {
if (isset($_POST)) {
if ($_FILES) {
$files = ProductsMaster::SaveTempAttachments($_FILES);
return json_encode($files);
$result = ['files' => $files];
Yii::$app->response->format = trim(Response::FORMAT_JSON);
return $result;
} /* else {
echo json_encode(['error' => 'No files found for pload.']);
} */
}
}
}
/**
* Uploaded Images Delete Action on Update Forms Action
* #return boolean
*/
public function actionDeleteImage() {
$key = $_POST['key'];
if (is_numeric($key)) {
$products_image = ProductsImages::find()->where(['id' => $key])->one();
unlink(Yii::getAlias('#webroot') . '/' . $products_image->image);
$products_image->delete();
return true;
} else {
unlink(Yii::getAlias('#webroot') . '/uploads/products/temp/' . $key);
return true;
}
}
/**
** Create Products
**/
public function actionCreate() {
//Products Images
// temp store image moved and save to database.. with generated forms..
if (count($model->images_array) > 0) {
$images_array = explode(',', $model->images_array);
if (!empty($images_array) && $model->images_array != '') {
foreach ($images_array as $image) {
$file = Yii::$app->basePath . '/uploads/products/temp/' . $image;
$rename_file = Yii::$app->basePath . '/uploads/products/' . $image;
rename($file, $rename_file);
$productsImages = new productsImages();
$productsImages->products_id = $model->id;
$productsImages->image_for = 'products';
$productsImages->image = 'uploads/products/' . $image;
$productsImages->created_at = time();
$productsImages->save();
}
}
}
}
?>
Here Model
I added a load function to the attachment model.
<?php
/*
* Save Temp Images
*/
public static function SaveTempAttachments($attachments) {
$files = "";
$allwoedFiles = ['jpg', 'png'];
if ($_FILES) {
$tmpname = $_FILES['ProductsMaster']['tmp_name']['products_image'];
$fname = $_FILES['ProductsMaster']['name']['products_image'];
if (!empty($attachments)) {
if (count($fname) > 0) {
//Loop through each file
for ($i = 0; $i < count($fname); $i++) {
//Get the temp file path
$tmpFilePath = $tmpname[$i];
//Make sure we have a filepath
if ($tmpFilePath != "") {
//save the filename
$shortname = $fname[$i];
$size = $attachments['ProductsMaster']['size']['products_image'][$i];
$ext = substr(strrchr($shortname, '.'), 1);
if (in_array($ext, $allwoedFiles)) {
//save the url and the file
$newFileName = Yii::$app->security->generateRandomString(40) . "." . $ext;
//Upload the file into the temp dir
if (move_uploaded_file($tmpFilePath, 'uploads/products/temp/' . $newFileName)) {
$files['initialPreview'] = Url::base(TRUE) . '/uploads/products/temp/' . $newFileName;
$files['initialPreviewAsData'] = true;
// $files['uploadExtraData'][]['is_post'] = 'new';
$files['initialPreviewConfig'][]['key'] = $newFileName;
}
}
}
}
}
}
}
return $files;
}
?>
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
I am not grabbing the selected value ($model->attribute) on a dropDownList in Yii2, what could be wrong? Thanks
This is the code that is located on a View:
$command = $connection->createCommand('SELECT att1
FROM table
ORDER By table_id ASC');
$rows = $command->queryAll();
$command->execute();
$listData = ArrayHelper::index($rows, null, 'table_id');
Then on the same View I call to $listData
<div class="row">
<div class="col-lg-9">
<?php Pjax::begin(['enablePushState' => false]); ?>
<?php $form = ActiveForm::begin(['id' => 'test-form', 'options' => ['data-pjax' => true]
]); ?>
<?= $form->field($model, 'attribute')->dropDownList($listData, ['prompt'=>'List of attributes.']); ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'test-button']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php Pjax::end(); ?>
</div>
</div>
This is the Controller:
public function actionTest()
{
$model = new TestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->insertTest();
return $this->renderAjax('test', ['model' => $model]);
} else {
return $this->renderAjax('test', ['model' => $model]);
}
}
The Model has the definition of $attribute and insertTest() is a function that use the value of $attribute to query onto a DB.
Thinking of you should use
ArrayHelper::map($listData, 'table_id', 'table_id');
Because you need a one-dimensional array.
And it's better to use the ActiveRecord for queries to the database.
ArrayHelper Docs
You are selecting only att1 from table so you should map this column
$listData = ArrayHelper::index($rows, 'att1');
for debug try modify your actionTest commenting $model->insertTest(); and using $model->save();
if the value is saved in db then you should check inside you $model->insertTest() function
public function actionTest()
{
$model = new TestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
// $model->insertTest();
$model->save();
return $this->renderAjax('test', ['model' => $model]);
} else {
return $this->renderAjax('test', ['model' => $model]);
}
}
you should use map in ArrayHelper
$listdata = ArrayHelper::map(CategoryModel::find()->orderBy(['table_id' => SORT_ASC])->all(), 'table_id', 'table_text');
Note: 'table_text' is table attribute that will appear in dropdown label.
I found the solution to that issue.
By doing this way the form was not able to save the submitted information.
$command = $connection->createCommand('SELECT att1
FROM table
ORDER By table_id ASC');
$rows = $command->queryAll();
$command->execute();
$listData = ArrayHelper::index($rows, null, 'table_id');
However, by this way the form is able to grab the value selected and put it into the variable.
$rows = table::find()->all();
$listData = ArrayHelper::map($rows,'table_id','att1');
renderPartial clientSide validation doesn't work. I want to render part of form with ajax. Ex.:
_form.php
$form = ActiveForm::begin([
'options' => [
'enableAjaxValidation' => true,
]
]);
$form->field($model, 'category_id')->dropDownList($category, [
'onchange'=>'
$.get( "'.Url::toRoute('/controller/params').'", { id: $(this).val() } )
.done(function( data ) {
$( "#offers-param-content" ).html( data );
}
);'
]);
Controller.php
public function actionParams($id)
{
$model = new Param();
$params = EavAttribute::find()->where(['category_id'=>$id])->all();
$this->renderPartial('_params', ['model' => $model, 'params' => $params];
}
_params.php
foreach($params as $item){
echo Html::activeTextInput('text', $model, $item->name);
}
If you want to enable client validation, then set this property to true.
$form = ActiveForm::begin([
'options' => [
'enableAjaxValidation' => true,
'enableClientValidation'=>true
]
]);
And use renderAjax() function in place of renderPartial() it will inject into the rendering result with JS/CSS scripts and files which are registered with the view
In your Controller.php you need to set layout to false and die the execution
public function actionParams($id)
{
$this->layout = false;
$model = new Param();
$params = EavAttribute::find()->where(['category_id'=>$id])->all();
$this->renderPartial('_params', ['model' => $model, 'params' => $params];
die;
}
Your not returning any validation errors from your controller to your view.
To archive that use
yii\widgets\ActiveForm::validate($yourModel);
If your not using activeform you can return errors by
$model->getErrors();//will return errors from $model->validate()
From your excerpt try this
public function actionParams($id) {
$model = new Param();
if ($model->load(Yii::$app->request->post())) {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($model); /* Validation error messages are returned by this static function */
}
$params = EavAttribute::find()->where(['category_id' => $id])->all();
$this->renderPartial('_params', ['model' => $model, 'params' => $params]);
}
}
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);
}); });');
?>