yii2 full calendar events won't drag - yii2

I am passing events from a database to the view. Using the latest calendar plugin.
However I cannot get the event to drag from one day to another.
Here is controller:
public function actionAllEventsmod()
{
$events = Events::find()->all();
$tasks = [];
$draggable = "fc-draggable fc-resizable";
foreach ($events as $eve) {
$event = new \yii2fullcalendar\models\Event();
$house = House::getHouseAddress($eve->house_id);
$details = $house->address_line_1 . " -- " . $house->city . " -- " . $house->comments;
$event->id = $eve->event_id;
$event->start = $eve->start;
$event->end = $eve->end;
$event->title = $eve->title;
$event->description = $details;
$event->className = $draggable;
$event->editable = true;
$event->backgroundColor = $eve->background_color;
$tasks[] = $event;
}
return $this->render('all-events', [
'events' => $tasks,
]);
}
view:
use yii\helpers\Html;
use yii\grid\GridView;
use yii\web\JsExpression;
$JSEventClick = <<<EOF
function(calEvent, jsEvent, view) {
alert(calEvent.title + ' -- ' + calEvent.description);
}
EOF;
$this->registerJs($JSEventClick);
?>
<?= yii2fullcalendar\yii2fullcalendar::widget(array(
'events' => $events,
'id' => 'calendar',
'clientOptions' =>[
'allDaySlot' => false,
'eventLongPressDelay' => 1500,
'selectLongPressDelay' => true,
'hiddenDays'=> [0],
'height' => 'auto',
'minTime' => '08:00:00',
'maxTime' => '20:00:00',
'selectable' => true,
'selectHelper' => true,
'select' => function(start, end, allDay) {
var title = prompt('Event Title:');
if (title) {
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
},
true // make the event "stick"
);
}
calendar.fullCalendar('unselect');
},
'droppable' => true,
'draggable' => true,
'editable' => true,
'eventStartEditable' => true,
'drop' => new JsExpression($JSDropEvent),
'select' => new JsExpression($JSCode),
'eventClick' => new JsExpression($JSEventClick),
'eventLimit' => true,
'eventDrop' => function(event, delta, revertFunc) {
alert(event.title + " was dropped on " + event.start.format());
if (!confirm("Are you sure about this change?")) {
revertFunc();
}
}),
'eventRender' => new JsExpression($JSEventRender),
'eventResize' => new JsExpression("
function(event, delta, revertFunc, jsEvent, ui, view) {
console.log(event);
}"),
],
));
?>
<?php
$JSCode = <<<EOF
function(start, end) {
var title = prompt('Event Title:');
var eventData;
if (title) {
eventData = {
title: title,
start: start,
end: end
};
$('#w0').fullCalendar('renderEvent', eventData, true);
}
$('#w0').fullCalendar('unselect');
}
EOF;
$JSDropEvent = <<<EOF
function(date) {
alert("Dropped on " + date.format());
if ($('#drop-remove').is(':checked')) {
// if so, remove the element from the "Draggable Events" list
$(this).remove();
}
}
EOF;
?>
<div class="well">
<pre>
Event Hover:
<?= Html::encode($JSCode); ?>
Event JSDropEvent:
<?= Html::encode($JSDropEvent); ?>
</pre>
</div>
</div>
Any help would be most appreciated.

Related

How to use ACF into JSON via ajax in Wordpress

I'm trying to use the Advanced Custom Field (ACF) plugin to return JSON via ajax in WordPress.
The below code correctly returns the JSON data of the posts but is not giving me the ACF data inside each post.
How can I get that ACF data into JSON?
PHP File
add_shortcode("owt-ajax-shortcode", "owt_wpl_run_shortcode");
function owt_wpl_run_shortcode() {
ob_start();
include_once plugin_dir_path(__FILE__) . 'views/owt-ajax-page-view.php';
$template = ob_get_contents();
ob_end_clean();
echo $template;
}
add_action("wp_enqueue_scripts", "owt_include_scripts");
function owt_include_scripts() {
wp_enqueue_script("jquery");
}
add_action("wp_ajax_owt_ajax_lib", "owt_lib_ajax_handler_fn");
add_action("wp_ajax_nopriv_owt_ajax_lib", "owt_lib_ajax_handler_fn");
function owt_lib_ajax_handler_fn() {
$param = isset($_REQUEST['param']) ? trim($_REQUEST['param']) : "";
global $wpdb;
if (!empty($param)) {
if ($param == "get_all_posts") {
$all_posts = get_posts(array(
"post_type" => "post",
"post_status" => "publish",
'posts_per_page' => 20,
'order' => 'DESC',
'orderby' => 'date',
'cat' => 66
));
header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
echo json_encode( $all_posts );
die;
}
}
wp_die();
}
JavaScript
<button id="btn-get-all-posts">Click to get All Posts</button>
<script>
jQuery(function () {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
jQuery("#btn-get-all-posts").on("click", function () {
var postdata = "action=owt_ajax_lib&param=get_all_posts";
jQuery.post(ajaxurl, postdata, function (response) {
console.log(response);
});
});
});
</script>
instead of use get_posts try your own query with WP_Query
here is an example code, please let me know if it works correctly(I didn't test it yet)
function owt_lib_ajax_handler_fn()
{
$param = isset($_REQUEST[ 'param' ]) ? trim($_REQUEST[ 'param' ]) : "";
if ( ! empty($param) ){
if ( $param == "get_all_posts" ){
$args = [
"post_type" => "post",
"post_status" => "publish",
"posts_per_page" => 20,
"order" => 'DESC',
"orderby" => 'date',
"category__in" => [ 66 ],
];
$all_posts = new WP_Query($args);
$json_response = [];
if ( $all_posts->have_posts() ){
while ( $all_posts->have_posts() ) {
$json_response[] = [
'title' => get_the_title(),
'content' => get_the_content(),
'acf_meta' => [
get_fields(get_the_ID()),
],
];
}
wp_send_json($json_response, 200);
wp_die();
}
else {
wp_send_json($json_response, 404);
wp_die();
}
}
}
wp_die();
}
please have a look as below:
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'post',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'color',
'value' => array('red', 'orange'),
'compare' => 'IN',
),
array(
'key' => 'featured',
'value' => '1',
'compare' => '=',
),
),
));
Please use below function:
add_action("wp_ajax_owt_ajax_lib", "owt_ajax_lib");
add_action("wp_ajax_nopriv_owt_ajax_lib", "owt_ajax_lib");
function owt_ajax_lib() {
$param = isset($_REQUEST['param']) ? trim($_REQUEST['param']) : "";
global $wpdb;
if (!empty($param)) {
if ($param == "get_all_posts") {
$args = [
"post_type" => "post",
"post_status" => "publish",
"posts_per_page" => 20,
"order" => 'DESC',
"orderby" => 'date',
"category__in" => [ 33 ],
];
$all_posts = new WP_Query($args);
$json_response = array();
if ( $all_posts->have_posts() ):
while ( $all_posts->have_posts() ) : $all_posts->the_post();
$json_response[] = [
'title' => get_the_title(),
'content' => get_the_content(),
'acf_meta' => [
get_fields( get_the_ID() ),
],
];
endwhile;
endif;
echo json_encode($json_response);
die;
}
}
die;
}

yii2fullcalendar eventDrop removes event.color and event.description

Im having problem with yii2fullcalendar eventDrop. I’ve made a JsExpression for eventDrop and eventRender as seen below.
The problem is, when I drag and drop an event to a different day and refresh the page, it loses it’s color, and description goes to undefined.
With eventRender I add color and description properties to event class.
I tried modifying fullcalendar.css and fullcalendar.min.css .fc-event with no success
Here's the code
<?php
$JsEventRender = 'function(event, element) {
element.addClass(event.description);
element.addClass(event.color);
}'
?>
<?php
$JsEventDrop = 'function(event, delta, revertFunc) {
var event_data = {
id: event.id,
titulo: event.title,
descripcion: event.description,
fecha_inicio: $.fullCalendar.formatDate(event.start, "YYYY-MM-DD"),
hora_inicio: $.fullCalendar.formatDate(event.start, "HH:mm"),
hora_termino: $.fullCalendar.formatDate(event.end, "HH:mm"),
fecha_termino: $.fullCalendar.formatDate(event.end, "YYYY-MM-DD"),
color: event.color,
};
if (!confirm("¿Está seguro que desea modificar la fecha y/o hora?")) {
revertFunc();
}
else {
$.ajax({
type: "POST",
url: "index.php?r=calendario/update" + "&id=" + event_data.id
+ "&titulo=" + event_data.titulo + "&descripcion=" + event_data.description
+ "&fecha_inicio=" + event_data.fecha_inicio + "&hora_inicio=" + event_data.hora_inicio
+ "&hora_termino=" + event_data.hora_termino + "&fecha_termino=" + event_data.fecha_termino
+ "&color=" + event_data.color,
success: function(json) {
alert("Fecha y/o hora modificada correctamente");
}
});
}
}'
?>
<?= yii2fullcalendar\yii2fullcalendar::widget([
'events' => $events,
'id' => 'calendar',
'options' => [
'lang' => 'es',
],
'clientOptions' => [
'selectable' => false,
'editable' => true,
'droppable' => true,
'header' => [
'left' => 'prev,next,today',
'center' => 'title',
'right' => 'month,agendaWeek,agendaDay,listDay',
],
'minTime' => '08:00',
'maxTime' => '21:00',
'height' => 'auto',
'snapDuration' => '00:05:00',
'eventRender' => new JsExpression($JsEventRender),
'eventClick' => new JsExpression($JsEventClick),
'eventDrop' => new JsExpression($JsEventDrop),
'eventResize' => new JsExpression($JsEventResize),
],
]);
?>
<?php
public function actionCreate($fecha_inicio, $fecha_termino)
{
$model = new Calendario();
$model->fecha_inicio = $fecha_inicio;
$model->fecha_termino = $fecha_termino;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index']);
}
return $this->renderAjax('create', [
'model' => $model,
]);
}
public function actionUpdate($id, $titulo, $descripcion, $fecha_inicio, $hora_inicio, $hora_termino, $fecha_termino, $color)
{
$model = $this->findModel($id);
$model->id = $id;
$model->titulo = $titulo;
$model->descripcion = $descripcion;
$model->fecha_inicio = $fecha_inicio;
$model->hora_inicio = $hora_inicio;
$model->hora_termino = $hora_termino;
$model->fecha_termino = $fecha_termino;
$model->color = $color;
$model->save();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index']);
}
return $this->renderAjax('update', [
'model' => $model,
]);
}
At first I thought it was an Url problem but it is not.
I've posted same issue in Yii Framework's Forum
https://forum.yiiframework.com/t/fullcalendar-eventdrop-removes-event-color-and-event-description/125790
To Do
As per discussion you need to use eventSources to dynamically load events and then re-fetch the events once they are updated.
How To
A major part can be covered from a previous answer I wrote earlier, which describes in detail how to use the eventSources option, so I will not go into those details. the only thing that differs from that answer is that you have to re-fetch the events when you drag & drop an event on the calendar and for that you are already using the option eventDrop where you are getting the event properties and sending an ajax call to update the event properties in the database, so all you need is to add
Create an action in your controller which returns the events list in the format described in the previous answer I mentioned.
List the url of that action in the eventSources option that takes an array of urls like ['/controller/action'].
Refetch the events once you update the event by calling refetchEvents method like below.
$('#calendar').fullCalendar('refetchEvents');
and this needs to be the last line of the script that you have for the eventDrop, so your complete code for the javascript will look like
$JsEventDrop = 'function(event, delta, revertFunc) {
var event_data = {
id: event.id,
titulo: event.title,
descripcion: event.description,
fecha_inicio: $.fullCalendar.formatDate(event.start, "YYYY-MM-DD"),
hora_inicio: $.fullCalendar.formatDate(event.start, "HH:mm"),
hora_termino: $.fullCalendar.formatDate(event.end, "HH:mm"),
fecha_termino: $.fullCalendar.formatDate(event.end, "YYYY-MM-DD"),
color: event.color,
};
if (!confirm("¿Está seguro que desea modificar la fecha y/o hora?")) {
revertFunc();
}
else {
$.ajax({
type: "POST",
url: "index.php?r=calendario/update" + "&id=" + event_data.id
+ "&titulo=" + event_data.titulo + "&descripcion=" + event_data.description
+ "&fecha_inicio=" + event_data.fecha_inicio + "&hora_inicio=" + event_data.hora_inicio
+ "&hora_termino=" + event_data.hora_termino + "&fecha_termino=" + event_data.fecha_termino
+ "&color=" + event_data.color,
success: function(json) {
alert("Fecha y/o hora modificada correctamente");
}
});
}
//this line will refetch the events on the calendar with the newly saved values
$("#calendar").fullCalendar("refetchEvents");
}'
I solved this by changing actionUpdate to it's default, and adding 2 new actions called actionUpdateDrop and actionUpdateResize, one for each of the JsExpressions, JsEventDrop and JsEventResize respectively. I discovered that eventRender doesn't work at all so I deleted it.
I also changed JsExpressions to call these actions without passing tittle, description, and color because these parameters are not needed in the update. And magically events now keeps it's description and color.
//CalendarioController.php
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index']);
}
return $this->renderAjax('update', [
'model' => $model,
]);
}
public function actionUpdateDrop($id, $fecha_inicio, $hora_inicio, $hora_termino, $fecha_termino)
{
$model = $this->findModel($id);
$model->fecha_inicio = $fecha_inicio;
$model->hora_inicio = $hora_inicio;
$model->hora_termino = $hora_termino;
$model->fecha_termino = $fecha_termino;
$model->save();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index']);
}
return $this->render('update', [
'model' => $model,
]);
}
public function actionUpdateResize($id, $hora_inicio, $hora_termino)
{
$model = $this->findModel($id);
$model->hora_inicio = $hora_inicio;
$model->hora_termino = $hora_termino;
$model->save();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index']);
}
return $this->render('update', [
'model' => $model,
]);
}
//Index.php
<p>
<?php
$JsEventDrop = 'function(event, delta, revertFunc) {
var event_data = {
id: event.id,
fecha_inicio: $.fullCalendar.formatDate(event.start, "YYYY-MM-DD"),
hora_inicio: $.fullCalendar.formatDate(event.start, "HH:mm"),
hora_termino: $.fullCalendar.formatDate(event.end, "HH:mm"),
fecha_termino: $.fullCalendar.formatDate(event.end, "YYYY-MM-DD"),
};
if (!confirm("¿Está seguro que desea modificar la fecha y/o hora?")) {
revertFunc();
}
else {
$.ajax({
type: "POST",
url: "index.php?r=calendario/update-drop" + "&id=" + event_data.id
+ "&fecha_inicio=" + event_data.fecha_inicio + "&hora_inicio=" + event_data.hora_inicio
+ "&hora_termino=" + event_data.hora_termino + "&fecha_termino=" + event_data.fecha_termino,
success: function(json) {
alert("Fecha y/o hora modificada correctamente");
}
});
}
}'
?>
</p>
<p>
<?php
$JsEventResize = 'function(event, delta, revertFunc) {
var event_data = {
id: event.id,
hora_inicio: $.fullCalendar.formatDate(event.start, "HH:mm"),
hora_termino: $.fullCalendar.formatDate(event.end, "HH:mm"),
};
if (!confirm("¿Está seguro que desea modificar la hora?")) {
revertFunc();
}
else {
$.ajax({
type: "POST",
url: "index.php?r=calendario/update-resize" + "&id=" + event_data.id
+ "&hora_inicio=" + event_data.hora_inicio + "&hora_termino=" + event_data.hora_termino,
success: function(json) {
alert("Hora modificada correctamente");
}
});
}
}'
?>
</p>

How to update multiple images in kartik Upload widget?

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;
}
?>

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 in Yii2 making values reset while updating the Active form

Here my problem is i have a form . In that i have dependent dropdown.
for example if i select company name it automatically selects the dependent company email and company phone number. This is working perfectly while creating. but the problem is while am updating the same form, the dependent value getting reset. so that makes me to select the company name for every time but i don't to be like that. once if i select the value while creating the value shouldn't change while updating also.
_form.php
<?= $form->field($model, 'employee_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Employeedetails::find()->all(),'id','employeecode'),
'language' => 'en',
'options' => [
'placeholder' => 'Select a employeecode ...',
'onchange' => '
$.post( "index.php?r=employeedetails/lists2&id='.'"+$(this).val().split("-")[0], function( data ) {
$( "select#claimprocess-claim_for" ).html( data );
}),
$.post( "index.php?r=employeedetails/lists3&id='.'"+$(this).val().split("-")[0], function( data ) {
$( "select#claimprocess-email" ).html( data );
}),
$.post( "index.php?r=employeedetails/lists1&id='.'"+$(this).val(), function( data ) {
$( "select#claimprocess-employee_name" ).html( data );
});',
],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
This is Controller code
controller.php
public function actionLists($id)
{
$countEmployeedetails = Employeedetails::find()
->where(['company_id' => $id])
->count();
$employeedetails = Employeedetails::find()
->where(['company_id' => $id])
->all();
if($countEmployeedetails>0){
foreach($employeedetails as $employee){
echo "<option value='".$employee->id."'>".$employee->employeecode."</option>";
}
}
else{
echo "<option>-</option>";
}
}
public function actionLists1($id)
{
$countEmployeedetails = Employeedetails::find()
->where(['id' => $id])
->count();
$employeedetails = Employeedetails::find()
->where(['id' => $id])
->all();
if($countEmployeedetails >= 0)
{
foreach($employeedetails as $employee)
{
echo "<option value='".$employee->id."'>".$employee->name."</option>";
}
}
else{
echo "<option>-</option>";
}
}
public function actionLists2($id)
{
$countEmployeedetails = Employeedetails::find()
->where(['id' => $id])
->count();
$employeedetails = Employeedetails::find()
->where(['id' => $id])
->all();
if($countEmployeedetails >= 0)
{
foreach($employeedetails as $employee)
{
// $arr["id"] . '-' . $arr['designation']
echo "<option value='".$employee->id. '-' .$employee->name. "'>".$employee->RelationName."</option>";
}
}
else{
echo "<option>-</option>";
}
}
Finally i found answer, actually mistake was mine, because here am using getting records based on company_id but here i have used approvaldetails table id so that is the mistake, after i changed it to company_id, now its working good
public function actionLists2($id)
{
$countEmployeedetails = Employeedetails::find()
->where(['company_id' => $id])
->count();
$employeedetails = Employeedetails::find()
->where(['company_id' => $id])
->all();
if($countEmployeedetails >= 0)
{
foreach($employeedetails as $employee)
{
// $arr["id"] . '-' . $arr['designation']
echo "<option value='".$employee->id. '-' .$employee->name. "'>".$employee->RelationName."</option>";
}
}
else{
echo "<option>-</option>";
}
}