Adding my code here where I want to add a condition if in SQL DB if i have value for checkbox (for example 4 then it should disable above three, this is similar to earlier condition i.e.
if 1st or 2nd or 1st and 2nd is checked in then 3rd and 4th should be disabled and if 3rd is checked then 1st,2nd and 4th should be disabled, if 4th is checked then 1st,2nd and 3rd should be disabled)
If i use directly the value from my DB and disable the checkbox then even if i uncheck it then state will not change of checkbox.
import streamlit as st
import pyodbc
import pandas as pd
from Az_Configuration_File import get_azure_connection_string
def disable_checkboxes():
## Dict with the disable conditions
disable = st.session_state.disable
## Current checkboxes' values
chk1, chk2, chk3, chk4 = (
st.session_state.chk1,
st.session_state.chk2,
st.session_state.chk3,
st.session_state.chk4,
)
## Logic to disable checkboxes
disable[1] = chk3 or chk4
disable[2] = chk3 or chk4
disable[3] = (chk1 and chk2) or chk4
disable[4] = (chk1 and chk2) or chk3
def main():
Uname = st.text_input('Username')
conn_str = get_azure_connection_string()
if not isinstance(conn_str, str):
raise ValueError("Connection string is not a string")
conn = pyodbc.connect(conn_str)
SQL_query = pd.read_sql_query("SELECT * FROM [dbo].[CheckboxTable] where [dbo].[CheckboxTable].[Username]=?" ,conn, params=[Uname])
st.write(SQL_query)
if "disable" not in st.session_state:
st.session_state.disable = {1: False, 2: False, 3: False, 4: False}
"**✔️ Disabling Checkboxes and Session State**"
disable = st.session_state.disable
checkbox1,checkbox2,checkbox3,checkbox4 = [None]*4
checkbox1i = st.checkbox("First", disabled=disable[1], on_change=disable_checkboxes, key="chk1")
if checkbox1i:
checkbox1 = 'Yes'
checkbox2i = st.checkbox("Second", disabled=disable[2], on_change=disable_checkboxes, key="chk2")
if checkbox2i:
checkbox2 = 'Yes'
checkbox3i = st.checkbox("Third", disabled=disable[3], on_change=disable_checkboxes, key="chk3")
if checkbox3i:
checkbox3 = 'Yes'
checkbox4i = st.checkbox("Fourth", disabled=disable[4], on_change=disable_checkboxes, key="chk4")
if checkbox4i:
checkbox4 = 'Yes'
#Username = 'Manish'
def write_to_database(conn_str, Username, checkbox1, checkbox2, checkbox3, checkbox4):
try:
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
insert_query = """
INSERT INTO [dbo].[CheckboxTable](Username, checkbox1, checkbox2, checkbox3, checkbox4)
VALUES (?, ?, ?, ?, ?)
"""
cursor.execute(insert_query, Username, checkbox1, checkbox2, checkbox3, checkbox4)
conn.commit()
conn.close()
st.success('Data Written to Database')
except Exception as e:
st.error(f'Error: {e}')
if st.button("Submit"):
Username = Uname # Use the username entered in the text input
write_to_database(conn_str, Username, checkbox1, checkbox2, checkbox3, checkbox4)
if name == “main”:
main()