Add confirm when drag and drop the kanban view in odoo 10 - python

I work with project.task model. I need to add confirmation for every stage change when user did the drag and drop. Is there any possible way.. I add validation error in write method. But Its not complete my wish. please help me

Finally I found the solution...
In this case you have to change the kanban_view.js file in web_kanban module. You can replace
add_record_to_column: function (event)
this function by this code in "kanban_view.js" file.
add_record_to_column: function (event) {
var self = this;
var column = event.target;
var record = event.data.record;
var data = {};
data[this.group_by_field] = event.target.id;
// display confirm message
if (confirm("Are you sure you want to change this stage?")){
//if click yes do this
this.dataset.write(record.id, data, {}).done(function () {
if (!self.isDestroyed()) {
self.reload_record(record);
self.resequence_column(column);
alert("You have change the stage!");
}
}).fail(this.do_reload);
}else{// if no reload the page and remain the tile in same satage
location.reload();
}},

On odoo 14, here this code:
Do search "_onAddRecordToColumn" in addons/web/static/src/js/views/kanban/kanban_controller.js
then override function (with inherited module) to this:
_onAddRecordToColumn: function (ev) {
var self = this;
var record = ev.data.record;
var column = ev.target;
if (confirm("Are you sure want to change this stage?")){
this.alive(this.model.moveRecord(record.db_id, column.db_id, this.handle))
.then(function (column_db_ids) {
return self._resequenceRecords(column.db_id, ev.data.ids)
.then(function () {
_.each(column_db_ids, function (db_id) {
var data = self.model.get(db_id);
self.renderer.updateColumn(db_id, data);
});
});
}).guardedCatch(this.reload.bind(this));
}else{
this.reload();
}
},

Related

How to check if a Firestore collection exists without knowing document name/ID with Python [duplicate]

Is there a way to check if a sub collection exists in firestore for nodejs?
Currently I am using doc.exists for documents but I need to check if a subcolletion exists within a document in order to write some data or not.
Yes, there is. You can use docs.length to know if the subcollection exists.
I made a sample to guide you, hope it helps.
this.db.collection('users').doc('uid')
.get().limit(1).then(
doc => {
if (doc.exists) {
this.db.collection('users').doc('uid').collection('friendsSubcollection').get().
then(sub => {
if (sub.docs.length > 0) {
console.log('subcollection exists');
}
});
}
});
Mateus' Answer didn't help me. Probably it has been changed over the time.
.collection(..).get() returns a QuerySnapshot which has the property size, so I just did:
admin.firestore
.collection('users')
.doc('uid')
.collection('sub-collection')
.limit(1)
.get()
.then(query => query.size);
To be more precise:
const querySnapshot = await admin.firestore().collection('users').doc('uid').collection('sub-collection').limit(1).get()
if (querySnapshot.empty) {console.log('sub-collection not existed')}
This is how I was able to check if a collection exists?
I target the document path first, then if it exists, It means the collection afterwards exists and I can access it.
> db.collection("collection_name").document("doc_name").get()
> .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
> #Override
> public void onComplete(#NonNull Task<DocumentSnapshot> task) {
> if(task.isSuccessful()){
> DocumentSnapshot result = task.getResult();
> if(result.exists()){
> *//this means the document exist first, hence the
> //collection afterwards the doc_name will
> //exist...now I can access the collection*
> db.collection("collection_name").document("doc_name").collection("collection_name2").get()
> .addOnCompleteListener(task1 -> { if(task1.isSuccessful()){
> ...
> } }); } } });
isEmpty property of QuerySnapshot returns true if there are no documents in the QuerySnapshot.
Thus you can simply check if isEmpty is true or false.
const subcolRef = collection(db, "parentCollectionTitle", "parentDocId", "subcollectionTitle")
const subcolSnapshot = await getDocs(subcollectionRef)
if (!subcolSnapshot.empty) {
console.log("subcol does exists!");
} else {
console.log("subcol does NOT exist!");
}
(Firebase v9)
This is NextJS (React) code for checking if a sub-collection "history" exists or not in collection "users" > doc>user-Id,
if it exists then take data in history, else keep have-history == false.
you can then use {havehistory?<></>:<></>} for showing different info, as per data.
const [history, setHistory] = useState([])
const [havehistory, setHavehistory] = useState(false)
if(user){
onSnapshot(query(collection(db, "users", user.uid,"history")), (querySnapshot) => {
if(querySnapshot){
const historyBro = querySnapshot.docs.map((doc) => {
return { ...doc.data(), id: doc.id };
});
setHistory(historyBro)
setHavehistory(true)
}
})
}
make sure your imported the required modules. e.g.
import { useState } from "react";
import {db} from '../firebase'
import { collection,doc, query, onSnapshot} from "firebase/firestore";
import Link from "next/link";

sending checkbox array from js to django views

I'm confused about how to do it via Ajax or Json, but how can I send the selection array (curCheck) on-click to Django views and receive it as a python array
javascript
document.getElementById('results').addEventListener('click', function(){
html_table = '<thead><tr><th>Currency</th><th>Amount</th><th>Symbol</th>><tr/><thead/>'
var checkElements = document.getElementsByClassName('ch');
for(var i =0; i< curname.length; i++){
if (checkElements[i].checked) {
var curChecked = curname[i];
var JsonArr = JSON.stringify(curChecked);
postcurChecked(JsonArr)
html_table += '<tr><td>' + curname[i] + '</td>';
}
}
document.getElementById('result_table').innerHTML = html_table;
},false;
ajax
function postsubChecked(curChecked) {
$.ajax({
"url": "http://127.0.0.1:8000/results/",
"type": "POST",
"data": {"checkbox": curChecked},
"headers": { 'X-CSRFToken': getCookie('csrftoken')}
})
}
in django
def currencyChecked(request):
body_unicode = request.body.decode('utf-8')
body_unicode = body_unicode.replace('%22','')
print(body_unicode) json_data = json.loads(body_unicode.read())
I would like to see the python array print to see it is passed to the back
but I keep getting this error:
json_data = json.loads(body_unicode.read()) AttributeError: 'str' object has no attribute 'read'
For getting the selected checkbox values and sending as an array using ajax you can use jquery like this:
consider you have multiple checkboxes and a button.
<input type="checkbox" name="imageName">
<input type="checkbox" name="imageName">
.......
<button id="deletePhoto">Delete</button>
after selecting multiple checkbox values click on this button. On clicking the below jquery will be triggered to make an arrya of selected checkbox values.
//jquery for getting the selelcted checkbox values
$(document).on("click","#deletePhoto",function(){
var favorite = [];//define array
$.each($("input[name='imageName']:checked"), function(){
favorite.push($(this).val());
});
alert("Photo Selected: " + favorite.join(", "));
if(favorite.length == 0){
alert("Select Photo to delete");
return false;
}
//ajax for deleting the multiple selelcted photos
$.ajax({type: "GET",
url: "/olx/deletePhotoFromEdit",
data:{
favorite:favorite
},
success: function(){
// put more stuff here as per your requirement
});
}
});
});
In the view you can get the array like this:
selected_photo = request.GET.getlist('favorite[]')

web2py: detect change in dropdown widget

How can we detect a change from a dropdown widget so that code can be executed?
Table loan references table services. Both have field called interest_rate. When I change loan.service via dropdown I'd like to reflect the corresponding interest_rate from services table to loan table.
How can this be achieved?
model
db.define_table('services',
Field('service_name',requires=[IS_NOT_EMPTY(),IS_NOT_IN_DB(db,'services.service_name')]),
Field('service_type','reference service_types',requires=IS_IN_DB(db,db.service_types.id,
'%(type_name)s',
error_message='not in table',
zero=None),
ondelete='RESTRICT',
),
Field('interest_rate','decimal(15,2)',requires=IS_DECIMAL_IN_RANGE(0,100)),
Field('max_term','integer'),
auth.signature,
format='%(service_name)s',
)
db.define_table('loan',
Field('service','reference services',requires=IS_IN_DB(db,db.services.id,
'%(service_name)s',
error_message='not in table',
zero=None),
ondelete='RESTRICT',),
Field('member_id','reference members',requires=IS_IN_DB(db,db.members.id,
'%(member_name)s',
error_message='not in table',
zero=None),
ondelete='RESTRICT',
label='Member'),
Field('amount','decimal(15,2)',requires=IS_DECIMAL_IN_RANGE(1000)),
Field('interest_rate','decimal(6,2)',default=10),
)
By using javascript in the front end. For example, using jquery library:
$("select").on("change", function(){
var selected = $(this).val();
$.ajax({
url: "/get_rates",
data:{
"selected": selected
},
success: function(value_from_url){
$("div").text(value_from_url);
}
});
});
The material process is to monitor onchange with the change() event, something like this:
<script src="{{=URL('static', 'js/utils.js')}}"></script>
<script>
{{=ASSIGNJS(jslast_nos = last_nos)}}
{{=ASSIGNJS(jsaction = action)}}
jQuery(document).ready(function(){
if (jsaction == "new") {
jQuery("#AAP_doc_number").val(jslast_nos[jQuery("#AAP_pos_id").val()]);
};
jQuery("#AAP_pos_id").change(function(){
pos_id = jQuery('#AAP_pos_id').val();
jQuery("#AAP_doc_number").val(jslast_nos[pos_id]);
});
jQuery('#AAP_bags').change(function(){
jQuery("#AAP_net_kg_qty").val(Number(jQuery('#AAP_bags').val() * 50));
jQuery('#AAP_net_kg_qty').change();
});
jQuery('#AAP_net_kg_qty, #AAP_selling_price').change(function(){
n = Number(jQuery('#AAP_net_kg_qty').val()) * Number(jQuery('#AAP_selling_price').val())
jQuery('#AAP_amount').val(evenRound(Number(n),2).toFixed(2))
});
});
</script>

graphene django relay: Relay transform error

Being very new to GraphQL, I have a graphene django implementation of a server with two models, following rather closely the graphene docs' example.
In graphiql, I can do this, and get a result back.
Following another relay tutorial, I'm intending to render the result of this query on screen.
My attempt looks like this:
class Note extends Component {
render() {
return(
<div> {this.props.store.title} </div>
)
}
}
Note = Relay.createContainer(Note, {
fragments: {
store: () => Relay.QL`
fragment on Query {
note(id: "Tm90ZU5vZGU6MQ==") {
id
title
}
}
`
}
});
class NoteRoute extends Relay.Route {
static routeName = 'NoteRoute';
static queries = {
store: Component => {
return Relay.QL`
query {
${Component.getFragment('store')}
}
`},
};
}
My browser's console shows the following error:
Uncaught Error: Relay transform error ``There are 0 fields supplied to the query named `Index`, but queries must have exactly one field.`` in file `/Users/.../src/index.js`. Try updating your GraphQL schema if an argument/field/type was recently added.
I've been trying to figure it out on my own with limited success.
Can someone point me in the right direction?
Thanks #stubailo for pointing me in the right direction. I made some adjustments, and now have a minimum example running like this:
NoteList = Relay.createContainer(NoteList, {
fragments: {
store: () => Relay.QL`
fragment N on NoteNodeConnection {
edges {
node{
id
title
note
}
}
}
`
}
});
class NoteRoute extends Relay.Route {
static routeName = 'NoteRoute';
static queries = {
store: Component => {
return Relay.QL`
query {
notes {
${Component.getFragment('store')}
}
}
`},
};
}

flask request.args.getlist returns empty list

I am new to web development and trying to solve the following problem. My app has several checkboxes and I need to get values of checked checkboxes. Later, I use those values in further data manipulations and pass the final result using ajax. When I try:
values = request.args.getlist('check')
print values
the list is empty.
values = request.values.getlist('check')
doesn't work ether.
Flask portion:
#app.route('/smiles_to_chemfig')
def smiles_to_chemfig():
smiles_mol = request.args.get("smiles_mol")
values = request.args.getlist('check')
print values
lst = ' '.join(values)
chemfig, pdflink = smiles_mol_to_chemfig(lst,'-i direct', smiles_mol)
return jsonify(outcome = chemfig, pdf_link = pdflink)
ajax:
$(function(){
$("button#smiles").on('click', function(){
if ($('textarea[name=smiles_mol]').val()=="") {
//$("#txt_area").html("PLEASE FILL OUT THIS FIELD !")
alert("PLEASE FILL OUT THIS FIELD !");
}
else {
$.getJSON('/smiles_to_chemfig', {
smiles_mol: $('textarea[name=smiles_mol]').val()
}, function(data) {
$("#txt_area").text(data.outcome);
console.log(data.outcome);
$("#pdf").attr('src', data.pdf_link);
});
}
return false;
});
});
I suspect, that it has something to do with ajax because if I do not implement ajax everything woks good but I need to use ajax. Any suggestions and comments are highly appreciated!

Categories