How make second validation in request class - request

i make form and this request go to controller store:
public function store(StoreTermRequest $request): RedirectResponse
{
$this->authorize('terms.create');
$request->addTerms();
return redirect(route('terms'));
}
rules of request:
public function rules()
{
return [
'start_date' => ['required', 'date'],
'end_date' => ['required', 'after_or_equal:start_date', 'date'],
'start_day' => ['required', 'date_format:H:i'],
'end_day' => ['required', 'after_or_equal:start_day', 'date_format:H:i'],
'start_break' => ['required', 'date_format:H:i'],
'end_break' => ['required', 'after_or_equal:start_break', 'date_format:H:i'],
'time_one_visit' => ['required', 'integer', 'min:1'],
'work_days' => ['present', 'required'],
'work_days.*' => ['present', 'required', new Enum(Days::class)],
'doctor' => [
'required', 'exists:doctors,id', 'integer',
],
];
}
then i make buisness logic, from generate date to single visits terms then i want check whether the given dates are free. that's why i want make second validation
public function addTerms()
{
$startDayInMonth = strtotime($this->start_date);
$endDayInMonth = strtotime($this->end_date);
$startDayOfHour = strtotime($this->start_day);
$endDayOfHour = strtotime($this->end_day);
$startBreak = strtotime($this->start_break);
$endBreak = strtotime($this->end_break);
$workingDays = $this->work_days;
$timeOneVisit = $this->time_one_visit * 60;
$doctor = $this->doctor;
$doctorBefore = [];
$dateVisitBefore = [];
$startVisitBefore = [];
$endVisitBefore = [];
$j = $startDayInMonth;
while ($endDayInMonth >= $j) {
if (!in_array(date('N', $j), $workingDays)) {
$j += 86400;
continue;
}
$j += 86400;
$i = $startDayOfHour;
while ($endDayOfHour > $i) {
if ($startBreak <= $i && $endBreak > $i) {
$i = $endBreak;
}
$validator = Validator::make(
[
'start_visit' => date('H:i', $i),
'end_visit' => date('H:i', $i + $timeOneVisit)
],
[
'start_visit' => [new FreeTerm()],
'end_visit' => [new FreeTerm()],
]
);
if ($validator->fails()) {
//
}
array_push($doctorBefore, $doctor);
array_push($dateVisitBefore, date('Y-m-d', $j));
array_push($startVisitBefore, date('H:i', $i));
array_push($endVisitBefore, date('H:i', $i + $timeOneVisit));
$i += $timeOneVisit;
}
}
for ($i = 0; $i < count($doctorBefore); $i++) {
DB::table('terms')->insert([
'doctor_id' => $doctorBefore[$i],
'date_visit' => $dateVisitBefore[$i],
'start_visit' => $startVisitBefore[$i],
'end_visit' => $endVisitBefore[$i]
]);
}
}
and its successful validation but what write here to return to form after fail with error message
if ($validator->fails()) {
//
}
i tried
return redirect()->to(route('terms.create'));
return back()->withErrors($validate->errors()->withinput();
and a lot of combinations around this in controller in request class, but i'm done.
i want to see clear answer because my english is not perfect :P

Related

Wordpress React JS based template website not working after upgrading to PHP 8.1

After switching from PHP 7.4.30 to PHP 8.1, my WordPress website, which was built by the original developer using React JS, started acting strangely. The menus stopped working and the home page became frozen and immovable.
Enable the debug and below are some of them.
Deprecated: Optional parameter $menu declared before required parameter $location is implicitly treated as a required parameter in \app\public\wp-content\themes**\functions\classes\Settings\Menu.php on line 22
**
<?php
namespace ThemeClasses\Settings;
class Menu
{
public function __construct()
{
add_action('after_setup_theme', [$this, 'registerNavMenus']);
add_filter('getMenuTree', [$this, 'getMenuTree'], 10, 2);
}
public function registerNavMenus()
{
register_nav_menus([
'header_menu' => __('Header Menu', 'siri'),
'footer_menu' => __('Footer Menu', 'siri'),
'footer_columns' => __('Footer Columns', 'siri'),
]);
}
public function getMenuTree($menu = [], $location)
{
$flatMenu = $menu;
$flatMenu = $this->getMenuItems($menu, $location);
$treeMenu = [];
$itemsRefs = [];
foreach ($flatMenu as $menuItemObj) {
$itemId = $menuItemObj->ID;
$parentId = $menuItemObj->menu_item_parent;
$itemsRefs[$itemId] = [
'name' => $menuItemObj->title,
'url' => $menuItemObj->url,
'target' => $menuItemObj->target,
'active' => $menuItemObj->active,
'ID' => $itemId,
'parentId' => $parentId,
'children' => [],
];;
if ($parentId == 0) {
$treeMenu[] = &$itemsRefs[$itemId];
} elseif (isset($itemsRefs[$parentId])) {
$itemsRefs[$parentId]['children'][] = &$itemsRefs[$itemId];
}
}
return $treeMenu;
}
private function getMenuItems($menu, $location)
{
// Get all locations
$locations = get_nav_menu_locations();
// Get object id by location
$menuObject = wp_get_nav_menu_object($locations[$location]);
// Check menu exists
if (!is_object($menuObject)) return [];
// Get menu items by menu slug
$menu = wp_get_nav_menu_items($menuObject->slug);
// Return menu post objects
return $menu;
}
}
**Deprecated: parse_str(): Passing null to parameter #1 ($string) of type string is deprecated in public\wp-content\themes**r\functions\classes\WordPressSecurity.php on line 364
// add the filter
add_filter('wp_admin_css', function($url, $file) {
errol_log($url);
// make filter magic happen here...
return $url;
}, 10, 2 );
}
public function removeWPVersion($src)
{
global $wp_version;
parse_str(parse_url($src, PHP_URL_QUERY), $query);
if (!empty($query['ver']) && $query['ver'] === $wp_version) {
$src = remove_query_arg('ver', $src);
}
return $src;
}

save the record of bulk sms sent into db laravel

i have taken the id and mobile_num from users table.i have to insert that id name in this table as user_id,mobile_num,and status(0,1) into another table(wc_sms_status).sendSMSFunction is working fine.
public function SendBulkSms()
{
$usersNumber = User::select('id','mobile_num')->whereIn('id', [5,6,7,8])->get();
foreach($usersNumber as $userNumber)
{
if (!$userNumber->mobile_num)
{
$this->sendSmsFunction($userNumber->mobile_num);
DB::table('wc_sms_status')->insert([
['user_id' => 'id'],
['mobile_num' => 'mobile_num'] // set the status=1 // how query can be changed?
]);
}
elseif($userNumber->mobile_num == exist && status == 0)
{
$this->sendSmsFunction($userNumber->mobile_num);
$this->save();
}
else{
}
}
}
Do this :
public function SendBulkSms()
{
//assuming there is a relationship between your model users and wc_sms_status called wcSmsStatus
$usersNumber = User::with('wcSmsStatus')->select('id','mobile_num')->whereIn('id', [5,6,7,8])->get();
foreach($usersNumber as $userNumber)
{
if (!$userNumber->mobile_num)
{
$this->sendSmsFunction($userNumber->mobile_num);
DB::table('wc_sms_status')->insert([
'user_id' => $userNumber->id,
'mobile_num' => $userNumber->mobile_num,
'status' => 1,
]);
} elseif ($userNumber->mobile_num && $userNumber['wcSmsStatus']->status === 0)
{
$this->sendSmsFunction($userNumber->mobile_num);
$this->save();
} else {
}
}
}
public function SendBulkSms()
{
$users = User::select('id','mobile_num')
->whereIn('id', [5,6,7,8])
->whereNotNull('mobile_num')
->get();
$bulkData = [];
foreach ($users as $user)
{
$this->sendSmsFunction($userNumber->mobile_num);
DB::table('wc_sms_status')->insert([
['user_id' => 'id'],
['mobile_num' => 'mobile_num'] // set the status=1 // how query can be changed?
]);
$bulkData[] = [
'user_id' => $user->id,
'mobile_num' => $user->mobile_num,
];
}
if (!empty($bulkData)) {
WcSmsStatus::insert($education); // change to your model name
unset($bulkData);
}
}
try to use in this way, it will insert bulk data, dont fergot to mention protected $fillable[] in model

How to apply datatable filter when my table is passed from js?

I have js code which gets results from a query and pastes table to a div.So table is created in js and set with js.how do I apply datatables filter in such a case?
if you are using ajax request filter ,So url parameter filter may help :
for example :
This is your ajax get request url :
$.get(root_url+'index/user?id='+id+'&name='+name+'&gender='+gender, function(response){
console.log(response);
});
And this how you can caught those parameter in cakephp
public function user(){
if ($this->request->is('ajax')) {
$id = $this->request->getQuery('id');
$name = $this->request->getQuery('name');
$gender = $this->request->getQuery('gender');
$condition = [];
if ($id){
$condition = ['Users.id' => $id];
}
if (name) {
$condition = ['Users.name' => $name];
}
if (gender) {
$condition = ['Users.gender' => $gender];
}
$user = $this->Users->find()
->select([
'Users.id',
'Users.name',
'Users.gender',
'Users.create_date',])
->where(condition);
response = ['user' => $user];
return $this->response->withType('application/json')
->withStringBody(json_encode($response));
} else {
return $this->redirect(['controller' => 'pages','action' => 'error404']);
}
}

how to calculate bundle product price from array of custom selection through parameter(post data)?

the data got from post is.
[productid] => 3
[product_type] => bundle
[bundle_option] => Array
(
[1] => Array
(
[0] => 1
[1] => 2
)
[2] => Array
(
[0] => 3
[1] => 4
)
)
[qty] => 1
how to calculate the bundle price for my selections. The magento core funtions are more preferable.
Please use below code:
public function getDisplayPrice($product) {
if($product->getFinalPrice()) {
return $product->getFormatedPrice();
} else if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) {
$optionCol= $product->getTypeInstance(true)
->getOptionsCollection($product);
$selectionCol= $product->getTypeInstance(true)
->getSelectionsCollection(
$product->getTypeInstance(true)->getOptionsIds($product),
$product
);
$optionCol->appendSelections($selectionCol);
$price = $product->getPrice();
foreach ($optionCol as $option) {
if($option->required) {
$selections = $option->getSelections();
$minPrice = min(array_map(function ($s) {
return $s->price;
}, $selections));
if($product->getSpecialPrice() > 0) {
$minPrice *= $product->getSpecialPrice()/100;
}
$price += round($minPrice,2);
}
}
return Mage::app()->getStore()->formatPrice($price);
} else {
return "";
}
}
I solved it by own method, not sure its acceptable or not.
$bundle_option = Mage::app ()->getRequest ()->getParam('bundle_option');
$bundle_option_array = call_user_func_array('array_merge', $bundle_option);
$price = Mage::Helper('airhotels/bundle')->getBundlePrice($productid,$bundle_option_array);
my helper file is
public function getBundlePrice($productId,$bundle_option_array) {
$product = new Mage_Catalog_Model_Product();
$product->load($productId);
$price=0;
$selectionCollection = $product->getTypeInstance(true)->getSelectionsCollection($product->getTypeInstance(true)->getOptionsIds($product), $product);
foreach($selectionCollection as $option)
{
if (in_array($option->getSelectionId(), $bundle_option_array)){
$price += $option->price;
}
}
return $price;
}

Yii2 Save multiple data in the db using foreach loop in actionCreate

In my project I want to insert multiple rows of data at a single time using the foreach loop. I have a variable which has array of elements.
For instance if my array has say 3 different elements. I want to save all these 3 elements in the 3 different db table rows. I also have other columns which are same for all the 3 array elements.
I have put them inside foreach statement but only the 1st elements gets saved. Is there any method I can achieve this?
My code
public function actionCreate($prodID)
{
$model = new ProductlinesStorage();
if ($model->load(Yii::$app->request->post())) {
$productlineID = Productlines::find()->where(['area_id' => $model->productline_id, 'product_id' => $prodID])->all();
foreach ($productlineID as $singleProductlineID) {
$model->productline_id = $singleProductlineID->productline_id;
$model->user_id = Yii::$app->user->identity->user_id;
$model->isNewRecord = true;
$model->save();
}
return $this->redirect(['/product/storage?id='.$prodID]);
} else {
return $this->renderAjax('create', [
'model' => $model,
'prodID' => $prodID,
]);
}
}
Only the productline_id is different other columns will have same data for all the prdouctline_id.
Thank You!!!
You have only one model object, and you are saving only to it.
Try this:
public function actionCreate($prodID)
{
$model = new ProductlinesStorage();
if ($model->load(Yii::$app->request->post())) {
$productlineID = Productlines::find()->where(['area_id' => $model->productline_id, 'product_id' => $prodID])->all();
foreach ($productlineID as $singleProductlineID) {
$model = new ProductlinesStorage();
$model->productline_id = $singleProductlineID->productline_id;
$model->user_id = Yii::$app->user->identity->user_id;
$model->isNewRecord = true;
$model->save();
}
return $this->redirect(['/product/storage?id='.$prodID]);
} else {
return $this->renderAjax('create', [
'model' => $model,
'prodID' => $prodID,
]);
}
}
maybe you can modify my code
public function actionCreate()
{
$model = new SemesterPendek();
$model->user_id = \Yii::$app->user->identity->id;
$model->npm = \Yii::$app->user->identity->username;
$modelsNilai = [new Nilai];
if ($model->load(Yii::$app->request->post())){
$model->waktu_daftar = date('Y-m-d h:m:s');
$model->save();
$modelsNilai = Tabular::createMultiple(Nilai::classname());
Tabular::loadMultiple($modelsNilai, Yii::$app->request->post());
// validate all models
$valid = $model->validate();
$valid = Tabular::validateMultiple($modelsNilai) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelsNilai as $indexTools =>$modelNilai) {
$modelNilai->id_sp = $model->id;
// $modelNilai->user_id = \Yii::$app->user->identity->id;
if (! ($flag = $modelNilai->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
}
} catch (Exception $e) {
$transaction->rollBack(); \Yii::$app->session->setFlash('error','gagal');
}
}
} else {
return $this->render('create', [
'model' => $model,
'modelsNilai' => (empty($modelsNilai)) ? [new Nilai] : $modelsNilai,
]);
}
}
You need to create a different object to save in different rows. For loop executes 3 times but every time same object is being updated. You can define new object and save each time. Below code will work
public function actionCreate($prodID)
{
$model = new ProductlinesStorage();
if ($model->load(Yii::$app->request->post())) {
$productlineID = Productlines::find()->where(['area_id' => $model->productline_id, 'product_id' => $prodID])->all();
foreach ($productlineID as $singleProductlineID) {
$model = new ProductlinesStorage();
$model->productline_id = $singleProductlineID->productline_id;
$model->user_id = Yii::$app->user->identity->user_id;
$model->isNewRecord = true;
$model->save();
}
return $this->redirect(['/product/storage?id='.$prodID]);
} else {
return $this->renderAjax('create', [
'model' => $model,
'prodID' => $prodID,
]);
}
}

Resources