Get Current User when creating record . Odoo 14 - javascript

I have a field many2one relation to res.users in point of sale like this :
user_id = fields.Many2one(
comodel_name='res.users', string='Responsible',
help="Person who uses the cash register. It can be a reliever, a student or an interim employee.",
default=lambda self: self.env.uid,
states={'done': [('readonly', True)], 'invoiced': [('readonly', True)]},
)
<field string="User" name="user_id"/>
I want to set it 'required' and empty field , but when saving record if the value of 'user_id' was empty , then get the current user.
I tried with this code , but required value was blocking:
#api.model
def _default_user_id(self):
if not self.user_id:
self.user_id = self.env.uid
else:
self.user_id = False
user_id = fields.Many2one(
comodel_name='res.users',
required=True,
help="Person who uses the cash register. It can be a reliever, a student or an interim employee.",
default=_default_user_id,
states={'done': [('readonly', True)], 'invoiced': [('readonly', True)]},
)
How can I do it ?
Thanks.

Change your default code
from
default=lambda self: self.env.uid,
to
default=lambda self: self.env.user,
EDIT-1
In this case, we need to override create() method instead of write logic in default function. With following code, it will check user_id field at the time of record create, if record doesn't have user_id, it will set current logged user.
#api.model
def create(self, vals):
if "user_id" not in vals:
vals.update({"user_id": self.env.user})
record = super().create(vals)
return record
EDIT-2
In this case, we need to write down default function.
def _default_user_id(self):
if not self.user_id:
return self.env.user
return False

Related

Extract only the value and not the column name in SQL with karate dsl

I am using Karate for my test scenarios for the requirement to update the contract plan by passing the plan Id's and I am retrieving the planId from the database and passing it to my request json.
But the problem I am facing it comes with the column name whereas I only need the value.
Below is the example of how I am fetching my Id by connecting to the database
`#Scenario1
Scenario:
use jdbc to validate
def config = { username: 'mmultapp', password: 'Mmu1t#pp', url: 'jdbc:db2://edb2dev3.momentum.co.za:60022/MMULTTST', driverClassName: 'com.ibm.db2.jcc.DB2Driver' }
def DbUtils = Java.type('wellness_core_utils.DbUtils')
def db = new DbUtils(config)
def productId = db.readRows('select PRODUCT_ID from MULTUSR1.PLANS order by PLAN_ID desc fetch first 1 rows only')
print productId`
And I am getting the results in this way
{
"PRODUCT_ID": 68
}
I only need to read the value of 68 so I that I can pass it to my json request
Thanks in advance
The query returns a key-value pair which you write in the query, Suppose you write
select PRODUCT_ID AS pId from MULTUSR1.PLANS order by PLAN_ID desc fetch first 1 rows only;
So It returns a PRODUCT_ID with the name pId. Later on, you can use that result as per your requirements
Let's try this in your instance.
def productId = db.readRows('select PRODUCT_ID from MULTUSR1.PLANS order by PLAN_ID desc fetch first 1 rows only').PRODUCT_ID;
const result = productId.PRODUCT_ID;
Notice: Please check the first type of your query result
Like It's in [] or {}
In above instance I consider it in {}
const result = [{ PRODUCT_ID: 87 }];
console.log(result[0].PRODUCT_ID);

How to put a string to make a query using PHP CodeIgniter

I have different strings that is made by multiple checkboxes when is checked and I would like to use this strings to make a query.
For example:
If I click a specific sequence of checkboxes this returns me this value of string: "SELECT Call_Setup FROM lte_kpi.vw_main_kpis_cidade_rate_daily WHERE node != 'UNKNOWN' and node = 'ABADIA DE GOIÁS' and date between '10/02/2017' and '10/18/2017' order by date"
I save this query into a variable called query1. What I would like is to put this variable (query1) like parameter to perform a query.
This is my model:
<?php
class Model_KPI_Customize extends CI_Model{
function kpi_customize_CustomQuery(){
$query = $this->db->query(/*I would like to put my string here !*/);
return $query->result();
}
}
?>
This is my Controller
public function highcharts_teste(){
$this->load->model('model_kpi_customize');
$data['kpi_customize_string_CustomQuery'] = $this->model_kpi_customize
->kpi_customize_CustomQuery();
}
And I have a view with multiple checkboxes and one paragraph element wich I would like to display the result of a query.
In the example above I would like to return the following values like this, because this is the result when I query it on Database:
99.73
99.48
99.51
99.40
99.23
99.34
99.29
99.10
99.23
99.11
Thanks everyone.
Bye =)
SELECT Call_Setup
FROM
lte_kpi.vw_main_kpis_cidade_rate_daily
WHERE
node != 'UNKNOWN' and
node = 'ABADIA DE GOIÁS' and
date between '10/02/2017' and '10/18/2017'
order by date
Can be written using active_record like below
$where = array(
'node' => 'ABADIA DE GOIÁS',
'date >=' => '10/02/2017',
'date <=' => '10/18/2017'
);
$this->db->select('Call_Setup')
->get_where('vw_main_kpis_cidate_rate_daily', $where )
->order_by("date", "asc");

How do i prevent creating the same user with the same info?

How do I check if the user already created the same LRN ?
and when I press the save button twice it creates two user with the same info
how do I prevent it ?
jQuery('#save_voter').submit(function(e){
e.preventDefault();
var FirstName = jQuery('.FirstName').val();
var LastName = jQuery('.LastName').val();
var Section = jQuery('.Section').val();
var Year = jQuery('.Year').val();
var LRN = jQuery('.LRN').val();
var Password = jQuery('.Password').val();
e.preventDefault();
if (FirstName && LastName && Section && Year && LRN && Password){
var formData = jQuery(this).serialize();
jQuery.ajax({
type: 'POST',
url: 'save_student.php',
data: formData,
success: function(msg){
showNotification({
message: "Student Successfully Added",
type: "success",
autoClose: true,
duration: 5
});
By creating a unique constraint on the username field. It seems that in your case the LRN field is the username field. Make it unique by
ALTER TABLE users ADD UNIQUE INDEX uname on users (LRN);
Then you can try something like this to tell the end user that the username is duplicated.
try{
$res =$connection->query(your user insert);
}catch(Exception $e){
echo 'Sorry already exists';
}
You need to do 3 steps :
Check manually First Name and Last Name already exists or not in PHP file
In resultset contains more than 0 records, then return false which means record already exists.
In JQuery, if its getting false, then show an error message that record already exists.
Further, as #kongkang said in comments that the field LRN is as username.
then still you need to do 3 steps :
Make that field as unique in database table
Add if condition on insertion query (PHP File) that if return false it means record already exists
in Jquery, if returning value is false, then show error message.
Add a unique index to your database for a unique field.I hope LRN is there for you. Then
MYSQL:
ALTER TABLE users ADD UNIQUE (LRN)
SQL SERVER:
ALTER TABLE [users] ADD CONSTRAINT UC_LRN UNIQUE ([LRN]);
When you try to insert duplicate LRN database error will come automatically for Codeigniter. Without it you have to check manually.

Django: Form with list of integers

I have a javascript application (in angular) that calls my django application. It uses lists of integers to filter the response. In Django I'm using a form to clean the data.
Javascript:
app.factory('SearchData',
function(){
return {
shop:[],
sort:'',
xhr:'',
brand:[],
};
});
app.factory('SearchQuery',
['$http', '$location', '$route', 'SearchData',
function($http, $location, $route, SearchData){
return {
getItems: function(){
return $http.get('/search/',{
params: SearchData,
responseType: 'json',
});
}
};
}
]);
Python form:
class SearchForm(forms.Form):
shop = forms.IntegerField(widget=forms.SelectMultiple(),required=False)
sort = forms.CharField(max_length=1, min_length=1, required=False)
brand = forms.IntegerField(widget=forms.SelectMultiple(),required=False)
I get a list of integers in shop and brand but I do not how to handle it on the django side. I don't want to use MultipleChoiceField as I need to supply choices in form (which creates an unnecessary query). All I want to do is have a list of integers.
The form above throws "Enter a whole number.". I could just ditch the form and use request.GET.getlist('shop') (which works). But I'd rather use a form if possible...
Update, for now I'm using a MultipleChoiceField and pass the choices before validation in the view. Like:
shops = request.GET.getlist('shop', None)
sf = SearchForm(request.GET)
sf.fields['shop'].choices = shops
It works, but it isn't pretty.
Use a custom widget/field:
from django import forms
from django.core.exceptions import ValidationError
class MultipleValueWidget(forms.TextInput):
def value_from_datadict(self, data, files, name):
return data.getlist(name)
class MultipleValueField(forms.Field):
widget = MultipleValueWidget
def clean_int(x):
try:
return int(x)
except ValueError:
raise ValidationError("Cannot convert to integer: {}".format(repr(x)))
class MultipleIntField(MultipleValueField):
def clean(self, value):
return [clean_int(x) for x in value]
class SearchForm(forms.Form):
shop = MultipleIntField()
You can use TypedMultipleChoiceField from Django forms with coerce=int and to avoid validation against predefined list of choices override the def valid_value(self, value): method:
class MultipleIntegersField(forms.TypedMultipleChoiceField):
def __init__(self, *args, **kwargs):
super(MultipleIntegersField, self).__init__(*args, **kwargs)
self.coerce = int
def valid_value(self, value):
return True
class SearchForm(forms.Form):
shop = MultipleIntegersField()
Udi's code is good, but there is a problem (under Django 1.11.7) if you want to use this as (say) a hidden field of a completely general user-input form. The problem is that if the user input fails to validate and is re-POSTed with corrections, the multi-valued POST data comes back the second time around as a repr of itself, i.e
['a','b'] comes back as ["['a', 'b']"] and further mangled with each re-POST
So I wrote the following function which can be used to repair the damage every time the view processes POST data. It's a hack, because it involves making request.POST temporarily mutable using a private variable. Also it doesn't properly handle lists of strings containing commas, escaped quotes etc.
def sanitize_keys( request, only=None):
""" Restore multi-valued keys that have been re-posted. there's a repr
in the round trip, somewhere.
only = list of keys to sanitize. Default is all of them."""
mutt = request.POST._mutable
request.POST._mutable = True
keylist = only or request.POST.keys()
for key in keylist:
v = request.POST.get(key)
if v.startswith("[") and v.endswith("]"):
#print( "Debug: sanitizing " + v )
sanitized=[]
for s in v[1:-1].split(','):
s = s.strip()
if s.startswith("'") and s.endswith("'"):
s=s[1:-1].replace("\\'","'")
sanitized.append(s)
#print( "Debug: sanitized= ", sanitized )
request.POST.setlist( key, sanitized)
request.POST._mutable = mutt
return
Usage (fragments):
class TestForm( forms.Form):
name = forms.CharField()
...
customer_iid = MultipleValueField( required=False)
...
# POST
sanitize_keys( request, only=('customer_iid',) )
#print( 'Debug: customer_iid', request.POST.getlist('customer_iid', []) )
form = TestForm( request.POST)

Create SQL sentece according to users input MySQL

what I want to do is this:
First have a form that has 5 input for example:
Name:
Career:
Experience:
City:
Speciality:
what I need to do is create a sql sentence according to the fields that are filled. If only 2 field were filled create a sql with only those fields. I don't have any idea how to do this besides creating a sql sentence for every possibility which turns out to be a pretty extensive work. i read that i could use store procedures, but again I don't know how I would do it. please help me!
well sorry if i didn't elaborate the question.
here is the deal i have diferent tables in mysql database
person
person_id
name
last_name
person_courses
person_id
course
person_carrer
person_id
carrer
person_experience
person_id
position
experience_description
experience_from_date
experience_to_date
all this tables are related to person by foreign_key (person_id)
then i have a page where user have 6 diferent inputs:
name:
last_name:
courses:
experience:(this fields search position and experience_description from table person_experience)
antiquity:(must obtain a sumatory of all person_experience)
the user must obtain results according to the fields he filled.
what i tried to do is create a complex SQL sentence using "%%" like this
select a.person_id, b.name, c.last_name, d.courses, f.experience, g.antiquity
from person a,
(
'SQL SENTENCE' WHERE NAME LIKE "%%"
) b,
(
'SQL SENTENCE' WHERE LAST_NAME LIKE "%%"
) c,
(
'SQL SENTENCE' WHERE COURSE LIKE "%%" GROUP BY PERSON_ID
) d,
(
'SQL SENTENCE' WHERE POSITION LIKE "%%" OR EXPERIENCE_DESCRIPTION LIKE "%%"
GROUP BY PERSON_ID
) f,
(
'SQL SENTECE'
WHERE 'SUMATORY OF ALL PERSON EXPERIENCE, (TO_DATE - FROM_DATE)/365 '>=0 (THIS ZERO WOULD CHANGE IF USER FILLS INPUT ANTIQUITY)
GROUP BY PERSON_ID
) g
WHERE a.person_id = b.person_id and c.person_id = b.person_id and d.person_id = c.person_id and f.person_id = d.person_id and g.person_id = f.person_id
and if the user fills any field i just put the value between '%value%' so this way i get the result, and i get results with this sql sentence but the problem is that if a person doesn't have a experience or carrer it is not shown in the result, so i need someway, as i said in the firstplace, just search in the database according to the users filled inputs.
for example in if the user fills:
carrer, experience: search all person with that carrer and that experience.
name: search all person even if they dont have carrer or course or experience with that name
PS: trying to create an sql sentece for every posibility would result in 64 sql senteces and i am not thinking about doing it!
THANK FOR ALL THE HELP IN ADVANCE
Here is something that may help:
$sql = array(); // initialize empty array for data
foreach(array("name", "career", "experience", "city", "speciality") as $key) { // iterate all the form controls
if(!empty($value = trim($_POST[$key]))) {
// the form input is filled, so we add it to data array (with proper escaping)
$sql["`".$key."`"] = "'".mysqli_real_escape_string($value)."'";
}
}
if(count($sql)) { // only if user had provided some data
// generate the final SQL statement
$sql = "INSERT INTO `table` ("
.implode(", ", array_keys($sql)).") VALUES (" // for example (`name`, `career`)
.implode(", ", array_values($sql)) . ")"; // for example ('Foo', 'Bar')
} else {
// no informations provided
}

Categories

Resources