Saving kartik select2 widget data with a model - javascript

Am using kartik select2 widget and i would like it to save data to the database by passing it to the controller.
I have tried this
1. the select2 widget
<?php $form = ActiveForm::begin(['id'=>$model->formName()]); ?>
<?php
echo $form->field($model, 'unitid')->widget(Select2::classname(), [
'data' => ArrayHelper::map($model2,'unitid','unitname'),
'language' => 'de',
'options' => ['multiple' => true, 'placeholder' => 'Select a Unit '],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
<?php ActiveForm::end(); ?>
The javascript code to save data on form submit which is on the view:
<?php
$script = <<< JS
$('form#{$model->formName()}').on('beforeSubmit', function(e)
{
var \$form = $(this);
console.log(\$form.serialize());
$.post(
\$form.attr("action"),
\$form.serialize()
)
.done(function(result) {
console.log("Succesifully saved" + result);
}).fail(function(err)
{
console.log("failed to save" + err);
});
return false;
});
JS;
$this->registerJs($script);
?>
This generates this output on the console(for the serialized form output
_csrf=TGMzaDRINnEHFgM5RjIPICc2bBoZAWZAOBIGAnAeVSF4GUQteThUFw%
3D%3D&Unitslocation%5Bunitid%5D=&Unitslocation%5Bunitid%5D%5B%5D=9
the output is always passed as a string that is after trying
echo json_encode($model->unitid);
On the controller it returns a string instead of an integer
that is
["5"]
How can i convert ($model->unitid) to integer for the post params

Just use
$model->unitid = (int) $model->unitid;
Thats all.

Related

php - Display Events with Form Submit (FullCalendar)

Good day!
I am working on a small personal project with FullCalendar. So in the code below, I have written a function that displays the events when the user searches for that event when a keyword is entered. (e.g. "meeting")
function load($pdo)
{
try {
if (isset($_POST['search'])) {
//run sql connection and query
$term = $_POST['term'];
$data = array();
$sql = "SELECT * FROM events WHERE keyword LIKE '%$term%'";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
//output events data from db in array using foreach loop
foreach ($result as $row) {
$description = $row['description'];
$sentence = preg_replace('/(.*?[?!.](?=\s|$)).*/', '\\1', $description);
if (($row['allDay'] == '1') == 1) {
$data[] = array(
'id' => $row["id"],
'title' => $row["title"],
'start' => $row["s_date"],
'description' => $sentence,
'end' => $row["e_date"],
'url' => "event.php?id=".$row['id'],
'backgroundColor' => $row['bg_color'],
'borderColor' => $row['brdr_Color'],
'keywords' => $row['keyword'],
'category' => $row['category']
);
} else {
$data[] = array(
'id' => $row["id"],
'title' => $row["title"],
'start' => $row["s_date"],
'description' => $sentence,
'end' => $row["e_date"],
'url' => "event.php?id=".$row['id'],
'backgroundColor' => $row['bg_color'],
'borderColor' => $row['brdr_Color'],
'keywords' => $row['keyword'],
'category' => $row['category']
);
}
}
//echo and convert array to JSON representation
echo json_encode($data);
}
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
}
//execute load function
load($pdo);
The results are echoed in a json_encoded function and are loaded from jQuery.
$(document).ready(function () {
var calendar = $("#calendar").fullCalendar({
displayEventTime: false,
editable: false,
header: {
left: "prev,next today",
center: "title",
right: "listMonth, month,agendaWeek,agendaDay",
},
eventRender: function (event, element, view) {
$(element).tooltip({
title: event.description,
});
},
events: "load.php",
});
});
After submitting the form/hitting the submit button, the events are not returned or displayed. Is there something I'm missing in my code, or am I missing a procedure?
I hope I described my issue to your best of understanding and I hope to learn from this and better improve my code in the future.

Validate form before submit

There is a form. The submit button does not apply to ActiveForm with id = "modal-btn-register-request". In JQuery, by clicking on this button I call $("#modal-btn-register-request").submit() and the form has been validated or not sent to the action. How can I validate before clicking the button. It's all about the button, if you insert the standard Html::submitButton, if there are errors in the form, the data is not sent
rules in model
public function rules()
{
return [
[['email'], 'required'],
[['email'], 'email'],
[['password','password_confirm'], 'required'],
];
}
form in view
<?php \yii\widgets\ActiveForm::begin(['action' => '/sign-up']); ?>
<?php echo $form->field($registerForm, 'email')->textInput(['placeholder' => 'Input login', 'class' => 'modal-login__input inp-main']); ?>
<?php echo $form->field($registerForm, 'password')->passwordInput(['placeholder' => 'Input password', 'class' => 'modal-login__input inp-main']) ?>
<?php echo $form->field($registerForm, 'password_confirm')->passwordInput(['placeholder' => 'Confirm the password','class' => 'modal-login__input inp-main']) ?>
<?php \yii\widgets\ActiveForm::end(); ?>
<div class="modal-login__form-btns-cont clearfix">
<div class="modal-login__form-btn-wp modal-login__form-submit-cont text-md-right float-md-right">
<a class="modal-login__submit-btn" id="modal-btn-register-request" href="">Come in</a>
</div>
</div>
jQuery code
$("#modal-btn-register-request").click(function() {
$("#w3").submit();
});
if there is an incorrect field, do not send the form and vice versa?
or how you can send the form when clicking on an element that does not belong to ActiveForm and take into account the validation
Use event.preventDefault() and the yiiActiveForm object:
$("#modal-btn-register-request").click(function(event) {
event.preventDefault();
jQuery('#w3').yiiActiveForm().submit();
});
try this
<?php \yii\widgets\ActiveForm::begin(['action' => '/sign-up']); ?>
<?php echo $form->field($registerForm, 'email')->textInput(['placeholder' => 'Input login', 'class' => 'modal-login__input inp-main']); ?>
<?php echo $form->field($registerForm, 'password')->passwordInput(['placeholder' => 'Input password', 'class' => 'modal-login__input inp-main']) ?>
<?php echo $form->field($registerForm, 'password_confirm')->passwordInput(['placeholder' => 'Confirm the password','class' => 'modal-login__input inp-main']) ?>
<div class="modal-login__form-btns-cont clearfix">
<div class="modal-login__form-btn-wp modal-login__form-submit-cont text-md-right float-md-right">
<a class="modal-login__submit-btn" id="modal-btn-register-request" href="">Come in</a>
</div>
</div>
<?php \yii\widgets\ActiveForm::end(); ?>
At first glance seems your button in not witnin the actual form.
Edit:
I think for what you need you can go about doing in two ways:
1) use an AJAX validation or
2)Use javascript (or JQuery if you prefer) in your view to process the fields before yo call $("#modal-btn-register-request").submit()
For (1) you can do like so:
Edit your form begin like so <?php \yii\widgets\ActiveForm::begin(['action' => '/sign-up', 'enableAjaxValidation' => true]); ?>
Next add the rule you want to verify ofr example:
public function rules()
{
return [
[['email'], 'required'],
[['email'], 'email'],
['email', 'unique'], //<---for example
[['password','password_confirm'], 'required'],
];
}
Now you would need to add to your action (the one that renders the form) an if statement to catch this AJAX call in your controller like so
public function actionSignup(){ //<-- assuming its the signup action
$model = new User();
if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())){
Yii::$app->response->format = 'json';
return ActiveForm::validate($model);
}
return $this->render('signup',[
'model' => $model
]);
}
If you want to validate without even checking in your database then is can be doe strictly with javascript (or JQuery) and option (2) is your choice. In that case check out the question check length of input field?
Hope this helps.

Getting null value when inserting data through Yii2 form

I've added a textinput field in my production form. The unitprice fills up when I select productname field drop down. But when I'm saving the data, I'm getting following error -
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'unitprice' cannot be null
The SQL being executed was: INSERT INTO `bottle` (`usedate`, `useqty`, `productname`, `bottlename`, `unitprice`) VALUES ('2016-04-21', '12', 'CEFO', 'Enter', NULL)
The last "NULL" is the value for unitprice.
actionCreate in productionController-
public function actionCreate()
{
$model = new Production();
$productname = new Productnames();
$bottle = new Bottle();
$bottlename = new Bottlename();
if ($model->load(Yii::$app->request->post()) && $productname->load(Yii::$app->request->post()))
{
$model->save();
//$bottle->attributes = $model->attributes;
$bottle->usedate = $model->productiondate;
$bottle->useqty = $model->prodqty;
$bottle->productname = $model->productname;
$bottle->bottlename = $productname->bottletype;
$bottle->unitprice = $bottlename->unitprice;
// $employee->emp_mobile = $model->emp_mobile;
$bottle->save();
return $this->redirect(['create']);
} else {
return $this->render('create', [
'model' => $model,
'bottle' => $bottle,
'productname' => $productname,
'bottlename' => $bottlename,
]);
}
}
Production _form
<?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
use yii\web\View;
use frontend\assets\XyzAsset;
use yii\helpers\ArrayHelper;
use dosamigos\datepicker\DatePicker;
use kartik\select2\Select2;
use frontend\modules\production\models\Productbatch;
use frontend\modules\production\models\Productnames;
use kartik\depdrop\DepDrop;
use yii\helpers\Json;
use frontend\modules\production\models\Bottlename;
//XyzAsset::register($this);
/* #var $this yii\web\View */
/* #var $model frontend\modules\production\models\Production */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="production-form">
<?php $form = ActiveForm::begin(); ?>
<!--<?= Html::a('Select Product', ['/production/productbatch/index'], ['class'=>'btn btn-primary']) ?> -->
<?= $form->field($model, 'productiondate')->widget(
DatePicker::className(), [
// inline too, not bad
'inline' => false,
// modify template for custom rendering
//'template' => '<div class="well well-sm" style="background-color: #fff; width:250px">{input}</div>',
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
<!-- echo CHtml::button("(+)",array('title'=>"Select Product",'onclick'=>'js:selectproductforproduction();')); -->
<?= $form->field($model, 'productname')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Productnames::find()->all(),'productnames_productname','productnames_productname'),
'language' => 'en',
'options' => ['placeholder' => 'Select Product Name', 'id' => 'catid'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?= $form->field($model, 'batchno')->widget(DepDrop::classname(), [
'options'=>['id'=>'subcat-id'],
'pluginOptions'=>[
'depends'=>['catid'],
'placeholder'=>'Select BatchNo',
'url'=>Url::to(['/production/productbatch/subcat'])
]
]); ?>
<?= $form->field($model, 'prodqty')->textInput() ?>
<?= $form->field($productname, 'bottletype')->textInput() ?>
<?= $form->field($bottlename, 'unitprice')->textInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
$script = <<< JS
$('#catid').change(function(){
var catid = $(this).val();
$.get('index.php?r=production/productnames/get-for-production',{ catid : catid }, function(data){
//alert(data);
var data = $.parseJSON(data);
$('#productnames-bottletype').attr('value',data.bottletype);
$('#bottlename-unitprice').attr('value',data.bottletype0.unitprice);
});
});
JS;
$this->registerJs($script);
?>
The action to get the data array
public function actionGetForProduction($catid)
{
$bottle = Productnames::find()->with('bottletype0')->where(['productnames_productname'=>$catid])->asArray()->one();
//$bottle -> select(['productnames.productnames_productname','productnames.bottletype','bottlename.unitprice'])->from('Productnames')->leftJoin('bottlename','productnames.bottletype = bottlename.bottlename')->where(['productnames_productname'=>$catid])->limit(1);
echo Json::encode($bottle);
This code works fine except the last unitprice. Please help.
You fotgot to add $bottlename->load(Yii::$app->request->post()) in if condition. So add like as,
if ($model->load(Yii::$app->request->post()) && $productname->load(Yii::$app->request->post()) && $bottlename->load(Yii::$app->request->post())) {
.......
}

MySQL data into FullCalendar

EDIT 2
I have the array at the correct format but nothing added to calendar:
EDIT
I want to get data from mysql and display it on fullcalendar. I have this PHP code:
<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('global.php');
//Json and PHP header
header('Content-Type: application/json');
$eventss = array();
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
$search_date = "SELECT * FROM appointment INNER JOIN patient ON appointment.patient_id = patient.id WHERE appointment.id_logged = :id_logged";
$search_date_stmt = $conn->prepare($search_date);
$search_date_stmt->bindValue(':id_logged', $id_logged);
$search_date_stmt->execute();
$search_date_stmt_fetch = $search_date_stmt->fetchAll();
$search_date_stmt_count = $search_date_stmt->rowCount();
foreach($search_date_stmt_fetch as $row)
{
$events[] = array( 'title' => $row['patient_name'], 'start' => date('Y-m-d',$row['date_app']), 'end' => date('Y-m-d',$row['date_app']), 'allDay' => false);
array_push($events, $event);
}
echo json_encode($event);
?>
The array that should be returned to fullcalendar so it can display it should be like:
'id'=>'value', 'title'=>'my title', 'start'=>...etc
But what the array I am seeing in the XHR is like:
Here is fullcalendar script (no errors at the console):
<script>
(function ($) {
$(document).ready(function() {
$('#calendar').fullCalendar({
eventSources: [
// your event source
{
url: 'fullcalendar/get-events.php',
error: function() {
alert('there was an error while fetching events!');
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
}
// any other sources...
]
});
});
})(jQuery);
</script>
I think you have problem with array you are using and you dont have ID for event, it supposee patient id to b I made some changes on your code please try it .
foreach($search_date_stmt_fetch as $row)
{
$event = array( 'id' => $row['patient_id'], 'title' => $row['patient_name'], 'start' => date('Y-m-d',strtotime($row['date_app'])), 'end' => date('Y-m-d',strtotime($row['date_app'])), 'allDay' => false);
array_push($events, $event);
}
echo json_encode($events);
You are mixing $event, $events and $eventss (unused).
It should read :
foreach($search_date_stmt_fetch as $row) {
$event = array( 'id' => $row['patient_id'], 'title' => $row['patient_name'], 'start' => date('Y-m-d',$row['date_app']), 'end' => date('Y-m-d',$row['date_app']), 'allDay' => false);
array_push($events, $event);
}
echo json_encode($events);
it depends on version of full calendar , there are two version v2 , v1
the required properties for the event object is title,start
if you are working with version v2, u need to convert the date to Moment, the version v2 is completely working on moment objects.
after getting the data from server, we can convert it like this
in js file:
$.map(data, function (me) {
me.title = me.title, // this is required
me.start = moment(me.start).format(); // this is required
me.end = moment(me.end).format();
}
$('#calendar').fullCalendar('addEventSource', data);

Jquery and PHP , autocomplete

So i just found out about the jquery auto complete and i would like to add it to my web-page. I want to hook it up to my php code so i can search my sql database. However Whenever i try to run my auto complete,it doesnt seem to find the php array im passing ( im just trying to get an array to work for now) . Can someone help?
Jquery Code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#tags" ).autocomplete({
source: "test.php"
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
PHP code
<?php
$data[] = array(
'c++','Java','JavScript',"c#" );
echo json_encode($data);
?>
This is an updated version of your answer which should resolve the deprecated SQL driver and the injection issue. You need to replace the SECOND_COLUMNNAME with your actual column's name. Aside from that I think this should work.
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=DB','username','password');
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
if(empty($_REQUEST['term']))
exit();
//require_once('connect.php'); connection to db is in this file so connection is not needed
$query = 'SELECT name, SECOND_COLUMNNAME FROM locations
WHERE name
LIKE ?
ORDER BY id ASC
LIMIT 0,10';
$stmt = $dbh->prepare($query);
$stmt->execute(array(ucfirst($_REQUEST['term']) . '%'));
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = array(
'label' => $row['name'],
'value' => $row['SECOND_COLUMNNAME']
);
}
echo json_encode($data);
flush();
Links:
http://php.net/manual/en/pdo.prepared-statements.php
http://php.net/manual/en/pdo.connections.php
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
How can I prevent SQL injection in PHP?
Also not sure if there was anything else inside connect.php, you might need to bring that back.
The array pattern used here should be as below.
<?php
$data = array(
array("value"=>'C++'),
array("value"=>'Java'),
array("value"=>'Javascript'),
array("value"=>'C#'),
);
echo json_encode($data);
If you're using PHP >= 5.4:
$data = [
[ 'value' => 'C++' ],
[ 'value' => 'Java' ],
[ 'value' => 'Javascript' ],
[ 'value' => 'C#' ]
];
echo json_encode( $data );
Here's a working example of my autocomplete code:
function get_data(type, target, min_length )
{
$(target).autocomplete({
source: function( request, response ) {
var submit = {
term: request.term,
type: type
};
$.ajax({
url: '/request/get',
data: { thisRequest: submit},
dataType: "json",
method: "post",
success: function( data ) {
response($.map( data.Data, function( item ) {
return {
label: item.label,
value: item.label
}
}));
}
});
},
minLength: min_length
})
}
<?php
$data = array(
'c++',
'Java',
'JavScript',"c#" );
echo json_encode($data);
?>
So i want with Pratik Soni advice and did a search. Here is the php code if anyone wants to use it
<?php
// Connect to server and select databse.
$dblink = mysql_connect('localhost','username','password') or die(mysql_error());
mysql_select_db('DB');
?>
<?php
if(!isset($_REQUEST['term']))
exit();
require('connect.php');
$term =
$query = mysql_query('
SELECT * FROM locations
WHERE name
LIKE "'.ucfirst($_REQUEST['term']).'%"
ORDER BY id ASC
LIMIT 0,10', $dblink
);
$data = array();
while($row = mysql_fetch_array($query, MYSQL_ASSOC)){
$data[] = array(
'label' => $row['name'],
'value' => $row['name'],
);
}
echo json_encode($data);
flush();

Categories

Resources