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);
}); });');
?>
Related
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.
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'];
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
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;