I want to make an input in the admin panel with which you can increase / decrease prices in several tables in db by % - laravel

I want to make an input in the admin panel with which you can increase / decrease prices in several tables in db by %.
At the moment, I did it through a filter
{
return [
new TwigSimpleFilter('price_kiev', [$this, 'formatPriceKiev'])
];
}
public function getPriceEditKiev()
{
$result = DB::table('another_pricelist_edit')->select('price_edit_kiev')->where('id', 1)->first();
return $result->price_edit_kiev;
}
public function formatPriceKiev($number)
{
$a = $this->getPriceEditKiev();
if ($a >= 1) {
$price = $number + $number / 100 * $a;
return round($price, -1);
}else{
return $number;
}
}
markup:
<td class="column-3">
{{ item.price_kiev_1 | price_kiev | number_format(0, '', ' ' ) }}</td>
admin panel with tables:
input where I enter the number for the filter, which I want to remake in order to use it to change the prices in the table by a percentage:
In short, how can I make an input in the admin panel with which I can update the prices in the tables in database?
maybe there are similar guides, I will be grateful
sql something like this:
update
table1
set
table1.price = (price + price)/100 * input;
select
*
from
table1;
where -> input: num %

You just need to make one dedicated action and ajax handler in your controller.
action to render HTML
ajax handler to handle the request when you submit the form
Note: Please change all the paths and the name according to your plugin
Add action and ajax handler plugins/hardiksatasiya/so/controllers/Items.php
class Items extends Controller
{
// other code ....
public function updateTable() {
// we want to show our menu as active
BackendMenu::setContext('HardikSatasiya.SO', 'main-menu-item-main', 'side-menu-item-update-items');
}
public function onUpdateTableAjax() {
$value = post('update_value');
if(!$value) {
Flash::error("please enter value");
return;
}
// write your table with your logic
Item::query()->update([
'value' => \DB::raw("value * $value")
// please sanitize post input and use here we just used it here as demo
]);
Flash::success("Successfuly updated tabel with value: $value");
}
}
Add HTML markup plugins/hardiksatasiya/so/controllers/items/updatetable.htm
<form
class="form-elements"
data-request="onUpdateTableAjax"
data-request-flash
>
<div class="form-group span-left">
<label>Update Table</label>
<input type="text" name="update_value" value="" class="form-control" />
</div>
<div class="form-group span-left">
<button type="submit" class="btn btn-default">Update Table</button>
</div>
</form>
Now you also need to show this action/html in frontend so the user can go there so we set menu item
update plugins/hardiksatasiya/so/plugin.yaml : side-menu-item-update-items <- we are adding this menu item
plugin:
name: 'hardiksatasiya.so::lang.plugin.name'
description: 'hardiksatasiya.so::lang.plugin.description'
author: hardikSatasiya
icon: oc-icon-star
homepage: ''
navigation:
main-menu-item-main:
label: Items
url: hardiksatasiya/so/items
icon: icon-star
sideMenu:
side-menu-item-main:
label: Items
url: hardiksatasiya/so/items
icon: icon-star
side-menu-item-update-items:
label: Settings
url: hardiksatasiya/so/items/updatetable
icon: icon-sliders
Please check the video for the output result
if any doubt please comment.

Related

Vue Js2 cant kep old data from laravel on select option

I am working on a crud operation with vue js and laravel. Everything works fine but I am thinking of a small improvement to make the site more user friendly. So where i click edit button all my inputs have they old value (fetched from laravel) except selected options. They do not update with the corresponding values from the db and when i edit an record this is a problem . How can i set old value or coresponding value on this option
form select for my options
<div class="form-group">
<label class="form-label select-label" for="team_foreman">Team Skill</label>
<select v-model="edit_team_skills" class="form-select" id="team_foreman" >
<option v-if="!skills.length" class="text-center" disabled>No data to show</option>
<option v-for="skill in skills" :value="skill.id" :key="skill.id" >{{skill.skills_name}}</option>
</select>
</div>
vue data
data() {
return {
edit_team_skills: '',
}
}
//edit method
editTeam(id) {
axios.get('/teams/'+id+'/edit')
.then(response => {
// console.log(response.data.teams.skills)
this.id = response.data.teams.id,
this.edit_team_name = response.data.teams.team_name
.....
this.edit_team_skills = response.data.teams.skills
})
},
laravel edit controller
public function edit($id)
{
$teams = Team::with('skills')->find($id);
return response()->json([
'teams' =>$teams,
], Response::HTTP_OK);
}
The v-model of the select should be an array of active option values, as you fill those with the id of the skill you should make this.edit_team_skills an array of id's.
this.edit_team_skills = response.data.teams.skills.map(skill => skill.id)

how to validate 2 fields with Minimum/Maximum compare validation in ionic3?

Working on reactive form group which contain 2 fields such as min and max, data is coming form hard-coded array data . when we enter the value on respective field just want to show validation that min value should be greater than max
Hope this will help you
create a form as bellow
createForm() {
this.personalDataForm = new FormGroup({
fieldOne: new FormControl("", [Validators.minLength(5), Validators.maxLength(15)])
// ...
});
}
add validations to your template
<form [formGroup]="personalDataForm">
<ion-row>
<label class="lbl-lnu">fieldOne :</label>
<input type="text" class="input-lnu" formControlName="fieldOne">
<div class="form-control-feedback" *ngIf="personalDataForm.controls.fieldOne.errors && (personalDataForm.controls.fieldOne.dirty || personalDataForm.controls.fieldOne.touched)">
<p class="error-msg" *ngIf="personalDataForm.controls.fieldOne.errors.minlength">Minimum length is 5</p>
<p class="error-msg" *ngIf="personalDataForm.controls.fieldOne.errors.maxlength">Maximun length is 15</p>
</div>
</div>
</ion-row>
</form>
to fire validation when submit, use bellow function
function isValid(): boolean {
const valid = this.personalDataForm.valid
if (!valid) { // if not valid fire validation
Object.keys(this.personalDataForm.controls).forEach(field => {
const control = this.personalDataForm.get(field);
control.markAsTouched({ onlySelf: true });
});
}
return valid; // if form data valid return true, otherwise false
}

Output user first name

I want to get the name of the user to put it on an h1.
What dies this line stand for?
#select="option => selected = option">
I'm using Buefy for the vue components.
<template>
<section>
<div class="field">
<b-switch v-model="keepFirst">
Keep-first <small>(will always have first option pre-selected)</small>
</b-switch>
</div>
<p class="content"><b>Selected:</b> {{ selected }}</p>
<b-field label="Find a name">
<b-autocomplete
v-model="name"
placeholder="e.g. Anne"
:keep-first="keepFirst"
:data="filteredDataObj"
field="user.first_name"
#select="option => selected = option">
</b-autocomplete>
</b-field>
</section>
</template>
<script>
import data from '#/assets/data_test.json'
// Data example
// [{"id":1,"user":{"first_name":"Jesse","last_name":"Simmons"},"date":"2016-10-15 13:43:27","gender":"Male"},
// {"id":2,"user":{"first_name":"John","last_name":"Jacobs"},"date":"2016-12-15 06:00:53","gender":"Male"},
// {"id":3,"user":{"first_name":"Tina","last_name":"Gilbert"},"date":"2016-04-26 06:26:28","gender":"Female"},
// {"id":4,"user":{"first_name":"Clarence","last_name":"Flores"},"date":"2016-04-10 10:28:46","gender":"Male"},
// {"id":5,"user":{"first_name":"Anne","last_name":"Lee"},"date":"2016-12-06 14:38:38","gender":"Female"}]
export default {
data() {
return {
data,
keepFirst: false,
name: '',
selected: null
}
},
computed: {
filteredDataObj() {
return this.data.filter((option) => {
return option.user.first_name
.toString()
.toLowerCase()
.indexOf(this.name.toLowerCase()) >= 0
})
}
}
}
</script>
# is shorthand for v-on:, so it's handling a select event with a function that receives option as a parameter and assigns it to selected.
Since v-model is bound to name, you should be able to do <h1>{{name}}</h1> to have the same value show up in an H1.
The data section has the main variables for your object. name is there. There is also a computed (named filteredDataObj) that should return an array (length of zero or one) with the matching test data. If you want other fields (like id) you would need to look there. Something like
{{filteredDataObj.length ? filteredDataObj.id : ''}}
would give the id if name matched anything in the data set.

How to show value inside input filed on change of drop down value using zend framework 2

I am trying to create an onchange event in zend framework 2. suppose if i change option form dropdown list then the related value will be shown on input field .Here my dropdown works fine .but when i am trying to change dropdown list then there is no value shows on my input field.but the data comes.but not display on broweser.So tell me how it is possible.
Here is My Controller
public function propratingAction()
{
$projectName = $this->propinquity()->projectName();
if($this->getRequest()->isPost())
{
$project =$this->getRequest()->getPost('project');
$projectD = json_decode($project, true);
//print_r($projectD);
$propinquityindex=$this->propinquity()->getproprating($projectD);
$propratingHTML=$this->propratingHTML($propinquityindex);
print_r($propratingHTML);
}
$viewModel = new ViewModel();
$viewModel->setVariables(array('key' => 'value'))
->setTerminal(true);
return $viewModel;
}
public function propratingHTML($propinquityindex){
$html='';
foreach ($propinquityindex as $value) {
# code...
$html .='<input type="text" value="'.$value['critics_rating'].'"/>';
}
print_r($html);
$viewModel = new ViewModel();
$viewModel->setVariables(array("key" => "value"))
->setTerminal(true);
return $viewModel;
}
Here is view part
<div style="display:inline-block; margin-left:55px; margin-top:20px;">
<select style="width:12.5em;" id="project_id" onchange="getsectorindexAjax();"
data-placeholder="Project Name" class="selectError2" data-rel="chosen"
name="project_id" >
<option value="">--select project--</option>
<?php if($this->projectName){
foreach($this->projectName as $val){
echo '<option value="'.$val['project_id'].'">'.$val['Project_name'].'
</option>';
}
} ?>
</select>
</div>
<div class="main" style="display:inline-block; margin-left:10px;margin-top:20px;">
CRc Rating
<input style="width:20em;height:2.7em;" name="critics_rating"
id="critics_rating" type="text" value="">
</div>
ajax call
function getsectorindexAjax()
{
require(["dojo/request", "dojo/query","dijit/registry"], function(request, registry) {
// Locate the JS object.
var project = dojo.byId("project_id").value;
//alert(project);
request.post("http://localhost/admin/propinquity/proprating",{
data : {
project : JSON.stringify(project)
}
}).then(function(text) {
dojo.byId("critics_rating").innerHTML = text;
console.log("return data : " + text);
});
});
}
So suggest me how can i show value inside input field when my dropdown value is change.
You can try something like this :
var dropdown= dijit.byId("project_id"); //get the select element
//on change event
dropdown.on('change', function(evt) {
//get the selected value
var project = dropdown.get("value");
//your ajax request
request.post("http://localhost/admin/propinquity/proprating",{
data : {
project : JSON.stringify(project)
}
}).then(function(text) {
dijit.byId("critics_rating").attr("value", text);
console.log("return data : " + text);
});
});

AngularJS: integrating with server-side validation

I have an angular app that contains a save button taken from the examples:
<button ng-click="save" ng-disabled="form.$invalid">SAVE</button>
This works great for client side validation because form.$invalid becomes false as user fixes problems, but I have an email field which is set invalid if another user is registered with same email.
As soon as I set my email field invalid, I cannot submit the form, and the user has no way to fix that validation error. So now I can no longer use form.$invalid to disable my submit button.
There must be a better way
This is another case where a custom directive is your friend. You'll want to create a directive and inject $http or $resource into it to make a call back to the server while you're validating.
Some pseudo code for the custom directive:
app.directive('uniqueEmail', function($http) {
var toId;
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
//when the scope changes, check the email.
scope.$watch(attr.ngModel, function(value) {
// if there was a previous attempt, stop it.
if(toId) clearTimeout(toId);
// start a new attempt with a delay to keep it from
// getting too "chatty".
toId = setTimeout(function(){
// call to some API that returns { isValid: true } or { isValid: false }
$http.get('/Is/My/EmailValid?email=' + value).success(function(data) {
//set the validity of the field
ctrl.$setValidity('uniqueEmail', data.isValid);
});
}, 200);
})
}
}
});
And here's how you'd use it in the mark up:
<input type="email" ng-model="userEmail" name="userEmail" required unique-email/>
<span ng-show="myFormName.userEmail.$error.uniqueEmail">Email is not unique.</span>
EDIT: a small explanation of what's happening above.
When you update the value in the input, it updates the $scope.userEmail
The directive has a $watch on $scope.userEmail it set up in it's linking function.
When the $watch is triggered it makes a call to the server via $http ajax call, passing the email
The server would check the email address and return a simple response like '{ isValid: true }
that response is used to $setValidity of the control.
There is a in the markup with ng-show set to only show when the uniqueEmail validity state is false.
... to the user that means:
Type the email.
slight pause.
"Email is not unique" message displays "real time" if the email isn't unique.
EDIT2: This is also allow you to use form.$invalid to disable your submit button.
I needed this in a few projects so I created a directive. Finally took a moment to put it up on GitHub for anyone who wants a drop-in solution.
https://github.com/webadvanced/ng-remote-validate
Features:
Drop in solution for Ajax validation of any text or password input
Works with Angulars build in validation and cab be accessed at formName.inputName.$error.ngRemoteValidate
Throttles server requests (default 400ms) and can be set with ng-remote-throttle="550"
Allows HTTP method definition (default POST) with ng-remote-method="GET"
Example usage for a change password form that requires the user to enter their current password as well as the new password.:
<h3>Change password</h3>
<form name="changePasswordForm">
<label for="currentPassword">Current</label>
<input type="password"
name="currentPassword"
placeholder="Current password"
ng-model="password.current"
ng-remote-validate="/customer/validpassword"
required>
<span ng-show="changePasswordForm.currentPassword.$error.required && changePasswordForm.confirmPassword.$dirty">
Required
</span>
<span ng-show="changePasswordForm.currentPassword.$error.ngRemoteValidate">
Incorrect current password. Please enter your current account password.
</span>
<label for="newPassword">New</label>
<input type="password"
name="newPassword"
placeholder="New password"
ng-model="password.new"
required>
<label for="confirmPassword">Confirm</label>
<input ng-disabled=""
type="password"
name="confirmPassword"
placeholder="Confirm password"
ng-model="password.confirm"
ng-match="password.new"
required>
<span ng-show="changePasswordForm.confirmPassword.$error.match">
New and confirm do not match
</span>
<div>
<button type="submit"
ng-disabled="changePasswordForm.$invalid"
ng-click="changePassword(password.new, changePasswordForm);reset();">
Change password
</button>
</div>
</form>
I have created plunker with solution that works perfect for me. It uses custom directive but on entire form and not on single field.
http://plnkr.co/edit/HnF90JOYaz47r8zaH5JY
I wouldn't recommend disabling submit button for server validation.
Ok. In case if someone needs working version, it is here:
From doc:
$apply() is used to enter Angular execution context from JavaScript
(Keep in mind that in most places (controllers, services)
$apply has already been called for you by the directive which is handling the event.)
This made me think that we do not need: $scope.$apply(function(s) { otherwise it will complain about $digest
app.directive('uniqueName', function($http) {
var toId;
return {
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
//when the scope changes, check the name.
scope.$watch(attr.ngModel, function(value) {
// if there was a previous attempt, stop it.
if(toId) clearTimeout(toId);
// start a new attempt with a delay to keep it from
// getting too "chatty".
toId = setTimeout(function(){
// call to some API that returns { isValid: true } or { isValid: false }
$http.get('/rest/isUerExist/' + value).success(function(data) {
//set the validity of the field
if (data == "true") {
ctrl.$setValidity('uniqueName', false);
} else if (data == "false") {
ctrl.$setValidity('uniqueName', true);
}
}).error(function(data, status, headers, config) {
console.log("something wrong")
});
}, 200);
})
}
}
});
HTML:
<div ng-controller="UniqueFormController">
<form name="uniqueNameForm" novalidate ng-submit="submitForm()">
<label name="name"></label>
<input type="text" ng-model="name" name="name" unique-name> <!-- 'unique-name' because of the name-convention -->
<span ng-show="uniqueNameForm.name.$error.uniqueName">Name is not unique.</span>
<input type="submit">
</form>
</div>
Controller might look like this:
app.controller("UniqueFormController", function($scope) {
$scope.name = "Bob"
})
Thanks to the answers from this page learned about https://github.com/webadvanced/ng-remote-validate
Option directives, which is slightly less than I do not really liked, as each field to write the directive.
Module is the same - a universal solution.
But in the modules I was missing something - check the field for several rules.
Then I just modified the module https://github.com/borodatych/ngRemoteValidate
Apologies for the Russian README, eventually will alter.
I hasten to share suddenly have someone with the same problem.
Yes, and we have gathered here for this...
Load:
<script type="text/javascript" src="../your/path/remoteValidate.js"></script>
Include:
var app = angular.module( 'myApp', [ 'remoteValidate' ] );
HTML
<input type="text" name="login"
ng-model="user.login"
remote-validate="( '/ajax/validation/login', ['not_empty',['min_length',2],['max_length',32],'domain','unique'] )"
required
/>
<br/>
<div class="form-input-valid" ng-show="form.login.$pristine || (form.login.$dirty && rv.login.$valid)">
From 2 to 16 characters (numbers, letters and hyphens)
</div>
<span class="form-input-valid error" ng-show="form.login.$error.remoteValidate">
<span ng:bind="form.login.$message"></span>
</span>
BackEnd [Kohana]
public function action_validation(){
$field = $this->request->param('field');
$value = Arr::get($_POST,'value');
$rules = Arr::get($_POST,'rules',[]);
$aValid[$field] = $value;
$validation = Validation::factory($aValid);
foreach( $rules AS $rule ){
if( in_array($rule,['unique']) ){
/// Clients - Users Models
$validation = $validation->rule($field,$rule,[':field',':value','Clients']);
}
elseif( is_array($rule) ){ /// min_length, max_length
$validation = $validation->rule($field,$rule[0],[':value',$rule[1]]);
}
else{
$validation = $validation->rule($field,$rule);
}
}
$c = false;
try{
$c = $validation->check();
}
catch( Exception $e ){
$err = $e->getMessage();
Response::jEcho($err);
}
if( $c ){
$response = [
'isValid' => TRUE,
'message' => 'GOOD'
];
}
else{
$e = $validation->errors('validation');
$response = [
'isValid' => FALSE,
'message' => $e[$field]
];
}
Response::jEcho($response);
}

Resources