check if dates are not within range before saving in yii - validation

how can i check if the dates posted in user's form exist in a range before saving? It's suppose to check different scenario date ranges. Below is just one of them. If it doesn't fall into range, it then posts.
is there a better way to do this?
$model = Table::model();
$criteria = new CDbCriteria;
//this is where i don't know how to get the values ($start,$end) from user before posting
$criteria->addCondition('start_date < '.$start);
$criteria->addCondition('end_date > '.$end);

You have to create custom validation function :
In rules add : this rules will work for both insert and update.
public function rules()
{
return array(
array('dateField', 'myCheckdate',),
);
}
In your custom validation function , you can apply your code to check the date range
public function myCheckdate($attribute,$params)
{
if(!$this->hasErrors())
{
if(Condition == false) // place your condition here
{
$this->addError($attribute,'The date is incorrect.');
}
}
}

Related

Prestashop 1.7.5 module - Update SQL custom table

I'm trying to add a new module to my shop to manage the sql table's values that I made. I can't find a proper guide that show me how to do that because all the forms have values contained in ps_configuration and not within a custom table.
How can I show those values in my form and get to update them?
Thank you if you'll take the time to answer that ^^
So, my form fields are still blank and they don't update my table when I submit.
I added this to "_construct" function:
public function __construct() {
$this->id_sell = $id_sell;
$this->country = $country;
$this->p_cod = $p_cod;
and this to "getContent"
public function getContent() {
$sqlV = 'SELECT * FROM `'._DB_PREFIX_.'mytable` WHERE id_sell = 1';
if ($row = Db::getInstance()->getRow($sqlV))
$country = $row[country];
$p_cod = $row[p_cod];
and last this on "getConfigFormValues":
protected function getConfigFormValues()
{
return array(
'country' => Tools::getValue('country'),
'p_cod' => Tools::getValue('p_cod'),
);
}
So, now I know that a need a class ObjectModel {}, too. Working on it.. and hoping for the best :D

Laravel set a common validator for all date fields in the system

I have different date fields in different models, I need to validate these date fields format on save of each model accordingly. is this possible?
Of course, you can. You just need to add this code below to your Model.
public static $rules = [
'date'=> 'reqired|date_format:MM:dd:YYYY' //if date is not required, ommite it
]
You can use different formats for your date in your different Models like MM:dd etc. Hope this helps you.
EDIT
To be able to use multiple date formats in a single validator You can define the multi-format date validation in your AppServiceProvider with the following code:
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Validator::extend('date_multi_format', function($attribute, $value, $formats) {
// iterate through all formats
foreach($formats as $format) {
// parse date with current format
$parsed = date_parse_from_format($format, $value);
// if value matches given format return true=validation succeeded
if ($parsed['error_count'] === 0 && $parsed['warning_count'] === 0) {
return true;
}
}
// value did not match any of the provided formats, so return false=validation failed
return false;
});
}
}
You can later use this new validation rule like that:
'date' => 'date_multi_format:"Y-m-d H:i:s.u","Y-m-d"' //or any other format
Hope this helps, thanks.

LARAVEL 5 How to store empty DateTime input to Null value instead of 0000:00:00 00:00 value

i had two input Datetime field.
User can choose to fill in either these two field.
For the empty input Datetime field, i want it to store as Null value in Database.
But currently the empty input Datetime field is store as 0000:00:00 00:00 value in Database. What code should i modified?
you can use model observers to unset the attribute before saving when it is empty. But be sure that the fields are nullable
class Flight extends Model
{
public static function boot()
{
parent::boot();
self::saving(function ($flight_model) {
if(empty($flight_model->arriveDateTime)) unset($your_model->attributes['your_date_field1'];
if(empty($flight_model->departDateTime)) unset($your_model->attributes['your_date_field2'];
});
}
}
this discussion would be a good reference
Update
to do the limitation in the controller you'll use required_without_all:foo,bar,... which as described in doc.s
The field under validation must be present and not empty only when all of the other specified fields are not present
to use it we'll add new rules like
$rules = array(
'arriveDateTime' => 'required_without_all:departDateTime',
'departDateTime' => 'required_without_all:arriveDateTime',
);
$validator = Validator::make(Input::all(), $rules);
and if you're using rules already just append this two roles to them. that's for the controller validation part.
for the view part I'll assume you've two inputs with id="arriveDateTime" and id="departDateTime" the code would be like
$(function() {
<!-- if the first input value changed disable the second input -->
$('#arriveDateTime').on('change', function() {
if ($(this).val() == '') {
$('#departDateTime').prop("disabled", false);
} else {
$('#departDateTime').prop("disabled", true);
}
});
<!-- if the second input value changed disable the first input -->
$('#departDateTime').on('change', function() {
if ($(this).val() == '') {
$('#arriveDateTime').prop("disabled", false);
} else {
$('#arriveDateTime').prop("disabled", true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" id="arriveDateTime" />
<input type="text" id="departDateTime" />
All you need is Eloquent Mutators.
Below a simplified example, basically from https://laravel.com/docs/5.4/eloquent-mutators#defining-a-mutator
class User extends Model
{
/* Set or mutate value of property */
public function setDateInputAttribute($value)
{
$this->attributes['date_input'] = $this->dateTimeOrNull($value);
}
/* This method should get another place, because it's not the core of this model */
private function dateTimeOrNull($value)
{
/*
Check if given datetime is valid. Yes? Return original $value
For simplicity, I use PHP's DateTime class
*/
if (DateTime::createFromFormat('Y-m-d H:i:s', $value) !== false) {
return $value;
}
/* Datetime is not valid. Return null */
return null;
}
}
Further
I suppose your datetime format is like yyyy-mm-dd hh:ii:ss
You can uses laravel mutators. Here's one for date of birth.
public function setDob($value)
{
$this->attributes['dob'] = strlen($value)? Carbon::createFromFormat('d/m/Y', $value) : null;
}

How to add a calculated field in the FormEvents::PRE_SUBMIT Event

In my listener I need to access my entity when in the FormEvents::PRE_SUBMIT event. In POST_SET_DATA this is no problem, just use $event->getData();.
So for the event listening to POST_SET_DATA I am fine with this code:
public function postSetData(FormEvent $event)
{
$form = $event->getForm();
$day = $event->getData();
$total = $this->dayManager->calculateTotal($day); // Passing a Day object, yay!
$form->get('total')->setData($total);
}
However in my method for the PRE_SUBMIT event.
I need this function because on submitting, total is not calculated with the newly submitted data.
public function preSubmit(FormEvent $event)
{
$form = $event->getForm();
// $day = $event->getData();
// Raw array because $event->getData(); holds the old not updated Day object
$day = $form->getData();
// Ough! Had to create and call a seperate function on my dayManager that handles the raw event array
$total = $this->dayManager->calculateTotalFromArray($event->getData());
// Modify event data
$data = $event->getData();
// Ough(2)! Have to do nasty things to match the raw event array notation
$totalArray = array(
'hour' => $total->format('G') . "",
'minute' => intval($total->format('i')) . ""
);
$data['total'] = $totalArray;
$event->setData($data);
}
As you can see, it works. However this is such a hackish way, I do not believe the pro's do it this way. Two things that go wrong here:
Cannot work with entity Day object in the preSubmit function
Have to create the calculateTotalFromArray function in the dayManager
Ugly code to match the raw event array in the preSubmit function
So the main question: how to get an updated Day object from the form in the PRE_SUBMIT form event.
Use SUBMIT instead of PRE_SUBMIT
Don't worry, the form is not yet submitted, SUBMIT is executed right before Form::submit
Why are you having this problem?
All data in PRE_SUBMIT has not been normalized into your usual object...
If you'd like to learn more about the whole thing, please head to: http://symfony.com/doc/current/components/form/form_events.html
Thanks #galeaspablo for submitting the answer! However I add below my code how I solved my particular problem.
My goal was to show a calculated total field in a form. Nothing more. However in the SUBMIT event you cannot do a $form->get('total')->setData($total);. You will get a warning: You cannot change the data of a submitted form.
So altering a form after PRE_SUBMIT is not possible. But adding fields is..
My complete solution is as follows:
In the DayType formbuilder:
// Will add total field via subscriber
//->add('total', TimeType::class, ['mapped' => false])
In the event subscriber:
class CalculateDayTotalFieldSubscriber implements EventSubscriberInterface
{
private $dayManager;
public function __construct(DayManager $dayManager)
{
$this->dayManager = $dayManager;
}
public static function getSubscribedEvents()
{
return array(
FormEvents::SUBMIT => 'addTotalField',
FormEvents::POST_SET_DATA => 'addTotalField'
);
}
public function addTotalField(FormEvent $event)
{
$form = $event->getForm();
$day = $event->getData();
$total = $this->dayManager->calculateTotal($day);
$form->add('total', TimeType::class, ['mapped' => false, 'data' => $total]);
}
}
Note the use of the save function for both the SUBMIT and the POST_SET_DATA events. A good read was: http://symfony.com/doc/current/components/form/form_events.html

How to check if the record exist using codeigniter

I'm creating a registration form using codeigniter. I understand that there is a validation for each field in CI but what I want to do is to validate a multiple field exist.
SELECT emp_id FROM emp_record WHERE firstname = 'firstname' AND lastname = 'firstname' AND birthdate = 'firstname'
If the query above find a match I want to alert on my view page that the record already exist.
Please help.
Appreciate it. Thanks.
Declare a custom callback function
function _check_firstname()
{
$firstname = $this->security->xss_clean($this->input->post('firstname'));
$array = array('firstname' => $firstname, 'birthdate' => $firstname);
$result = $this->db->select('emp_id')->from('emp_record')->where($array)->get();
if($result->num_rows())
{
$this->form_validation->set_message('_check_firstname', 'Record already exists');
return false;
}else
{
return true;
}
}
Set rules including (callback__check_firstname)
$this->form_validation->set_rules('firstname', 'First Name', 'trim|required|callback__check_firstname');
Now, when you'll check validation like
if ($this->form_validation->run()){
// passes
}
else{
// not passes, so show the view again
}
In the view, if you have something like this
<?php echo form_error('firstname') ?>
This will show the error message set in the custom callback function.
You could use num_rows() to do such things.
By using active record you can achieve this by doing the following
$qry = $this->db->select('emp_id')->from('emp_record')
->where('firstname', $firstname)
->where('lastname', $lastname)
->where('birthdate', $birthdate)
->get();
if ($qry->num_rows() > 0)
return TRUE;
else
return FALSE;
This will return TRUE if it finds at least one row in your database or FALSE if it finds nothing.
some people can/may have the same firstname,lastname and birthdate
But still if you want to have it that way you could create a callback validation
here is a snippet.
public function checkinput()
{
// you may want to sanitize the input
$data['fname'] = $this->input->post('fname');
$data['lname'] = $this->input->post('fname');
$data['mname'] = $this->input->post('fname');
//your model for checking data must return TRUE or FALSE
if($this->model->method_for_checking($data))
{
this->form_validation->set_message('checkinput', 'Duplicate data exists.');
return TRUE;
}else{
return FALSE;
}
}
Now you can use it on your validation rules i.e
$this->form_validation('fname','fname',callback_checkinput);
Other options are
Extend a form validation and create a validation rule there as not
to clutter the controller
Or ,After Submitting the form before inserting the data, you can check whether it is a duplicate and do the logical things their.

Resources