My holidays table is as follows
public function up() {
Schema::create('holidays', function (Blueprint $table) {
$table->increments('id');
$table->integer('created_by');
$table->string('holiday_name');
$table->date('start_date');
$table->date('end_date');
$table->text('description');
$table->tinyInteger('publication_status');
$table->tinyInteger('deletion_status')->default(0);
$table->timestamps();
});
}
My working_days table is as below
public function up() {
Schema::create('working_days', function (Blueprint $table) {
$table->increments('id');
$table->integer('updated_by');
$table->string('day', 10);
$table->tinyInteger('working_status')->comment('0 for holiday & 1 for working day');
$table->timestamps();
});
}
I store in my Holiday table a start_date = 2022-05-13 and an end_date = 2022-05-20. If I apply for a leave selecting start_date as 2022-05-13 and end_date as 2022-05-20 the code below is executed properly
if($monthly_holidays != null){
return redirect()->route('leave.index')->with('exception', 'You select a holiday !');
}
Saying You select a holiday
If I apply for a leave for non holiday dates the code below is executed properly and the dates are saved with the correct number of leaves (Sunday and Saturday are not counted and this is ok)
if($monthly_holidays == null){
$result = Leave::create($leave_application +['num_days' => $days] +['reason' =>request('reason')] + ['created_by' => auth()->user()->id]);
$inserted_id = $result->id;
if (!empty($inserted_id)) {
return redirect()->route('leave.index')->with('message', 'Add successfully.');
}
return redirect()->route('leave.index')->with('exception', 'Operation failed !');
}
However If I select Sunday and Saturday my code below does not work the way I should expect because Sunday and Saturday dates are saved as leaves
if($weekly_holidays != null){
foreach ($weekly_holidays as $weekly_holiday) {
if ($sdates == $weekly_holiday['day'] && $edates == $weekly_holiday['day']) {
return redirect()->route('leave.index')->with('exception', 'You select a holiday !');
}
}
The complete code is as follows
public function store(Request $request) {
$sdates = date("D", strtotime($request->start_date));
$edates = date("D", strtotime($request->end_date));
$leave_application = $this->validate($request, [
'leave_category_id' => 'required',
'start_date' => 'required',
'end_date' => 'required',
]);
$start_date = Carbon::parse(request('start_date'));
$end_date = Carbon::parse(request('end_date'));
$days = $start_date->diffInWeekdays($end_date);
$weekly_holidays = WorkingDay::where('working_status', 0)
->get(['day'])
->toArray();
$monthly_holidays = Holiday::where('start_date', '=', $request->start_date)->where('end_date', '=',$request->end_date)
->first(['start_date','end_date']);
if($monthly_holidays == null){
$result = Leave::create($leave_application +['num_days' => $days] +['reason' =>request('reason')] + ['created_by' => auth()->user()->id]);
$inserted_id = $result->id;
if (!empty($inserted_id)) {
return redirect()->route('leave.index')->with('message', 'Add successfully.');
}
return redirect()->route('leave.index')->with('exception', 'Operation failed !');
}
if($weekly_holidays != null){
foreach ($weekly_holidays as $weekly_holiday) {
if ($sdates == $weekly_holiday['day'] && $edates == $weekly_holiday['day']) {
return redirect()->route('leave.index')->with('exception', 'You select a holiday !');
}
}
}
if($monthly_holidays != null){
return redirect()->route('leave.index')->with('exception', 'You select a holiday !');
}
}
I am not able to figure out how to skip weekends. Weekend like sun and sat still recorded in the leave table. please help
I have changed the Holiday table to store just holiday date to make it simple
public function up() {
Schema::create('holidays', function (Blueprint $table) {
$table->increments('id');
$table->integer('created_by');
$table->string('holiday_name');
$table->date('holiday_date');
$table->text('description');
$table->tinyInteger('publication_status');
$table->tinyInteger('deletion_status')->default(0);
$table->timestamps();
});
}
and made some changes to my store methods as follows
public function store(Request $request) {
$sdates = date("D", strtotime($request->start_date));
$edates = date("D", strtotime($request->end_date));
$leave_application = $this->validate($request, [
'leave_category_id' => 'required',
'start_date' => 'required',
'end_date' => 'required',
]);
$start_date = Carbon::parse(request('start_date'));
$end_date = Carbon::parse(request('end_date'));
$days = $start_date->diffInWeekdays($end_date);
$weekly_holidays = WorkingDay::where('working_status', 0)
->get(['day'])
->toArray();
if($weekly_holidays != null){
foreach ($weekly_holidays as $weekly_holiday) {
if ($sdates == $weekly_holiday['day'] || $edates == $weekly_holiday['day']) {
return redirect()->route('leave.index')->with('exception', 'You select a weekend !');
}
}
}
$monthly_holidays = Holiday::where('holiday_date', '=', $request->start_date)
->first(['holiday_date']);
if($monthly_holidays == null){
$result = Leave::create($leave_application +['num_days' => $days] +['reason' =>request('reason')] + ['created_by' => auth()->user()->id]);
$inserted_id = $result->id;
if (!empty($inserted_id)) {
return redirect()->route('leave.index')->with('message', 'Add successfully.');
}
return redirect()->route('leave.index')->with('exception', 'Operation failed !');
}
if($monthly_holidays != null){
return redirect()->route('leave.index')->with('exception', 'You select a holiday !');
}
}
When I mistakenly set my leave on Sunday or Saturday and submit. My exception works and says You select a weekend
Related
I am inserting the data. The data is being entering quite fine but whenever I enter a letter the entry is done but that entry is converted to '0'.
This is my controller store function:
public function store(GuidanceReportRequest $request)
{
$stats = GuidanceReport::where('user_id', $request->user_id)->whereDate('created_at', now())->count();
if ($stats > 0) {
Session::flash('warning', 'Record already exists for current date');
return redirect()->route('reports.index');
}
if ((!empty($request->call_per_day[0]) && !empty($request->transfer_per_day[0])) ||
(!empty($request->call_per_day[1]) && !empty($request->transfer_per_day[1])) || (!empty($request->call_per_day[2])
&& !empty($request->transfer_per_day[2]))
) {
foreach ($request->category as $key => $value) {
$catgeory_id = $request->category[$key];
$call_per_day = $request->call_per_day[$key];
$transfer_per_day = $request->transfer_per_day[$key];
if (!empty($catgeory_id) && !empty($call_per_day) && !empty($transfer_per_day)) {
GuidanceReport::create([
"user_id" => $request->user_id,
"categories_id" => $catgeory_id,
"call_per_day" => $call_per_day,
"transfer_per_day" => $transfer_per_day,
]);
}
}
} else {
GuidanceReport::create($request->except('category', 'call_per_day', 'transfer_per_day'));
}
Session::flash('success', 'Data Added successfully!');
return redirect()->route('reports.index');
}
This is my Validation Request code
public function rules()
{
$rules = [];
$request = $this->request;
if ($request->has('transfer_per_day')) {
if (!empty($request->transfer_per_day)) {
$rules['transfer_per_day'] = "numeric";
}
}
if ($request->has('call_per_day')) {
if (!empty($request->call_per_day)) {
$rules['call_per_day'] = "numeric";
}
}
if ($request->has('rea_sign_up')) {
if (!empty($request->rea_sign_up)) {
$rules['rea_sign_up'] = "numeric";
}
}
if ($request->has('tbd_assigned')) {
if (!empty($request->tbd_assigned)) {
$rules['tbd_assigned'] = "numeric";
}
}
if ($request->has('no_of_matches')) {
if (!empty($request->no_of_matches)) {
$rules['no_of_matches'] = "numeric";
}
}
if ($request->has('leads')) {
if (!empty($request->leads)) {
$rules['leads'] = "numeric";
}
}
if ($request->has('conversations')) {
if (!empty($request->conversations)) {
$rules['conversations'] = "numeric";
}
}
return $rules;
}
Although I check the type in which request is being sent from controller and recieved from the request validation and it is Object. So how can I solve the issue.
I am working on yii2. I have came across a point in which I have to send an email to a person when a meter is installed and it's images are uploaded to the server. Fro this I have already configured the swift mailer.
There is a model named Installations which have a function which saves all the installation data.
public static function saveAll($inputs){
$coutner = 0;
$arr_status = [];
foreach ($inputs as $input) {
$s = new Installations;
foreach ((array)$input as $key => $value) {
if($key != 'image_names') {
if ($s->hasAttribute($key)) {
$s->$key = $value;
}
}
}
$user = Yii::$app->user;
if (isset($input->auth_key) && Users::find()->where(['auth_key' => $input->auth_key])->exists()) {
$user = Users::find()->where(['auth_key' => $input->auth_key])->one();
}
$s->created_by = $user->id;
if (Installations::find()->where(['ref_no' => $input->ref_no])->exists()) {
$arr_status[] = ['install_id' => $input->install_id, 'status' => 2, 'messages' => "Ref # Already exists"];
continue;
}
$s->sync_date = date('Y-m-d H:i:sāā');
if($s->save()){
if ($s->istallation_status == 'Installed') {
Meters::change_status_byinstall($s->meter_msn, Meters::$status_titles[4]);
}
else if ($s->istallation_status != 'Installed' && $s->comm_status =='Failed')
{
Meters::change_status_byinstall($s->meter_msn, Meters::$status_titles[5]);
}
$arr_status[] = ['install_id' => $input->install_id, 'status' => 1];
$coutner++;
if (isset($input->doc_images_name)) {
foreach ($input->doc_images_name as $img) {
$image = new InstallationImages;
$image->image_name = $img->image_name;
$image->installation_id = $s->id;
$image->save();
}
}
if (isset($input->site_images_name)) {
foreach ($input->site_images_name as $img2) {
$image2 = new InstallationImagesSite;
$image2->image_name = $img2->image_name;
$image2->installation_id = $s->id;
$image2->save();
}
}
}else{
$arr_status[] = ['install_id' => $input->install_id, 'status' => 0, 'messages' => $s->errors];
}
$status = $s->istallation_status;
$msn = $s->meter_msn;
$com = $s->comm_status;
// want to pass these variables to the controller function
}
return ['status' => 'OK', 'details' => $arr_status, 'records_saved' => $coutner];
}
Now There Is a Controller name InstallationController. This controller contains all the APIs for my mobile application. Below are two main functions in it
public function actionAddnew()
{
$fp = fopen('debugeeeeeee.txt', 'w+');
fwrite($fp, file_get_contents('php://input'));
fclose($fp);
$inputs = json_decode(file_get_contents('php://input'));
return Installations::saveAll($inputs);
}
public function actionSavephoto()
{
try {
$count = 0;
foreach ($_FILES as $f) {
$dd = pathinfo($f['name']);
if (!isset($dd['extension']) || !in_array($dd['extension'], array('jpg', 'png', 'gif'))) {
return ['status' => 'ERROR', 'uploaded_files' => $count, 'message' => 'Invalid File'];
break;
}
if (move_uploaded_file($f['tmp_name'], Installations::UPLOAD_FOLDER . $f['name'])) {
$count++;
return ['status' => 'OK', 'uploaded_files' => $count];
break;
} else {
return ['status' => 'ERROR', 'uploaded_files' => $count];
break;
}
}
} catch (Exception $x) {
return ['status' => 'ERROR', 'message' => $x->getMessage()];
}
}
The mobile application will call the Addnew() api and after that it will call the savephoto. Now I want to pass $msn,$status and $com values from the Model to the controller function Savephoto.
For this I have tried to use session variables but still I am unable to get by desired result(s).
I have also checked the question Yii, how to pass variables to model from controller?
but it didn't worked for me.
How can I achieve it?
Any help would be highly appreciated.
The only way to get those values out of saveAll() is to return them. Presently, they are defined on an object in $s that is overwritten each loop. The best way to do that seems to be creating an array outside of your foreach ($inputs... loop and appending each created Installations object.
Return that at the end, and pass it (or just the relevant element from it) into actionSavephoto() as a parameter. Then, those values will be accessible of properties of that passed object. This handling will occur in the code that is not pictured which calls actionAddNew() and then actionSavephoto()
i have added two date fields. i want to retrieve the data between those two table.PaymentDate and ChequePostedDate are two fields. so i need to get the rows between two dates.
simply search content have two date fields. i want to retrieve the rows(data) between those two dates
public function __construct($modelClass, $fields = null, $filters = null) {
$fields = new FieldList(array(
DateField::create('PaymentDate','Payment Date : from')
->setConfig('dateformat', 'yyyy-MM-dd')
->setConfig('showcalendar', true)
->setAttribute('placeholder','YYYY-MM-DD')
->setDescription(sprintf(
_t('FormField.Example', 'e.g. %s', 'Example format'),
Convert::raw2xml(Zend_Date::now()->toString('yyyy-MM-dd'))
)),
DateField::create('ChequePostedDate','cr Date : to')
->setConfig('dateformat', 'yyyy-MM-dd')
->setConfig('showcalendar', true)
->setAttribute('placeholder','YYYY-MM-DD')
->setDescription(sprintf(
_t('FormField.Example', 'e.g. %s', 'Example format'),
Convert::raw2xml(Zend_Date::now()->toString('yyyy-MM-dd'))
)),
));
$filters = array(
'PaymentDate' => new PartialMatchFilter('PaymentDate'),
'ChequePostedDate' => new PartialMatchFilter('ChequePostedDate'),
);
parent::__construct($modelClass, $fields, $filters);
}
public function getQuery($searchParams, $sort = false, $limit = false, $existingQuery = null) {
$dataList = parent::getQuery($searchParams, $sort, $limit, $existingQuery);
$params = is_object($searchParams) ? $searchParams->getVars() : $searchParams;
$query = $dataList->dataQuery();
if(!is_object($searchParams)) {
if (isset($params['PaymentDate'])&& $params['ChequePostedDate'] ) {
$query->where('`PaymentNote`.PaymentDate BETWEEN \''.$params['PaymentDate'].' \' AND \''.$params['ChequePostedDate'].'\'');
}
}
return $dataList->setDataQuery($query);
}
}
You can also use WithinRangeFilter something like the following, but you need to use the setMin(), setMax() methods as per this forum response: https://www.silverstripe.org/community/forums/form-questions/show/11685
public function getQuery($searchParams, $sort = false, $limit = false, $existingQuery = null) {
$dataList = parent::getQuery($searchParams, $sort, $limit, $existingQuery);
$params = is_object($searchParams) ? $searchParams->getVars() : $searchParams;
$query = $dataList->dataQuery();
if(!is_object($searchParams)) {
if (!empty($params['PaymentDate'] && !empty($params['ChequePostedDate'])) {
return $dataList->filter('PaymentDate:WithinRange', [$params['PaymentDate'], $params['ChequePostedDate']]);
}
}
return $dataList;
}
i solved it..
simply remove $filters
$filters = array(
// 'PaymentDate' => new PartialMatchFilter('PaymentDate'),
//'ChequePostedDate' => new PartialMatchFilter('ChequePostedDate'),
);
then it works
If I run the login function it prints User.
public function actionLogin(){
if ($model->load(Yii::$app->request->post()) && $model->login()) {
if (Yii::$app->user->isGuest) {
echo "guest";
} else {
echo "User";
}
return $this->redirect(['dashboard']);
}
After redirect If I run the dashboard function it prints guest.
public function actionDashboard()
{
if (Yii::$app->user->isGuest) {
echo "guest";
} else {
echo "User";
}
}
My Login model:
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
} else {
return false;
}
}
This is getUser function:
protected function getUser()
{
if ($this->_user === null) {
$this->_user = Customer::findByEmail($this->email);
}
return $this->_user;
}
Please help me to check in another function whether or not the user is logged in?
I successfully fixed this problem.
just change the backend/config/main.php or frontend/config/main.php
change this
'components' => [
'user' => [
'identityClass' => 'common\models\Customer', //or Any models you want
'enableAutoLogin' => true,
],
]
I've changed my codes a lot.
this is the code in my controller:
public function actionRequestTV() {
$this->layout = '//layouts/column1';
$this->bodyclass = 'bodygrey_without_leftbg';
$model = new Reqtv();
if (isset($_POST['Reqtv'])) {
if ($model->validate()) {
$model->attributes = $_POST['Reqtv'];
if ($model->save())
$this->redirect(array('step2', 'id' => $model->REQTVID));
}
}elseif (isset($_POST['BP'])) {
if ($model->validate()) {
$model->attributes = $_POST['BP'];
if (!$model->save()) {
print_r($model->getErrors());
}else
$this->redirect(array('step2B', 'id' => $model->REQTVID));
}
}else
$this->render('reqtvform_step1', array(
'model' => $model,
));
}
here is the rules :
public function rules() {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('BPID, SK', 'numerical', 'integerOnly' => true),
array('BPMOBILE', 'numerical'),
array('TVID, TVPASS', 'length', 'max' => 50),
array('PROBLEM', 'length', 'max' => 250),
array('BPCP, BPMOBILE, BPEMAIL', 'length', 'max' => 255),
array('SK', 'ceksk'),
array('BPEMAIL', 'email'),
array('PSNO', 'cekPSNO'),
// array('SK, PROBLEM, TVID, TVPASS', 'required', 'on' => 'step2'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('REQTVID, BPID, TVID, TVPASS, PROBLEM, SK, BPCP, BPMOBILE, BPEMAIL, PSNO', 'safe', 'on' => 'search'),
);
}
after changing my code from this code into more simple like the code above, it already able to save the values. but, some rules doesn't work, like ceksk rule. this is the code of ceksk:
public function ceksk() {
if($this->SK){
if (!$this->SK == 1) {
$this->addError('SK', 'Maaf, anda harus mencentang persetujuan syarat & ketentuan sebelum melanjutkan');
return false;
}
}
}
UPDATE
my ceksk rule is already work. but I'm decided to use JQuery instead:
<?php
Yii::app()->clientScript->registerScript('JQuery', "
$('#kirim').click(function() {
if ($('#SK').attr('checked')) {
return true;
}else{
alert('Anda belum mencentang Syarat & Ketentuan');
return false;
}
});
");
?>
but my other rules still won't work. my cekPSNO rule is working actually. but when it catch the error, it bring me to a blank white page instead of staying in the form page and show the error. this is the code:
public function cekPSNO() {
if ($this->PSNO) {
$psno = Ps::model()->findByAttributes(array('PSNO' => $this->PSNO));
//check cdsn ada atau tidak
if ($psno === null) {
$this->addError('PSNO', 'Nomor PS tidak ditemukan, silahkan periksa Nomor PS anda !');
return false;
} else {
if (date('Y-m-d') > $psno->TGLBERAKHIR) {
$this->addError('PSNO', 'Premium Support sudah expired !');
return false;
}
}
}
}
please, your help are absolutely appreciated. thank you :))
if(!$this->SK == 1) is not going to produce the result you want.
Try with if($this->SK != 1).
See http://php.net/manual/en/language.operators.precedence.php
The negation from the ! occurs before the comparison operator, which means you are effectively executing ((!$this->SK) == 1).
This will cause the code block to never execute, for if $this->SK is present and can type type-juggled to true, then its negation will result on a false value, which when compared to 1 (a true value) is never true. Whereas if $this->SK is empty or type-juggles to false, the incorrect comparison later will never be executed, so your validation will never report failure.
try this:
public function ceksk($attribute) {
if (!$this->$attribute == 1)
$this->addError($attribute, 'Maaf, anda harus mencentang persetujuan syarat & ketentuan sebelum melanjutkan');
}
source:
http://www.yiiframework.com/wiki/168/create-your-own-validation-rule/