Skip to content

Commit

Permalink
Added: immutable_context update on edit / dupl logic (#276)
Browse files Browse the repository at this point in the history
  • Loading branch information
signebedi committed Jun 30, 2024
1 parent cc41eb6 commit 707594f
Show file tree
Hide file tree
Showing 5 changed files with 75 additions and 46 deletions.
77 changes: 39 additions & 38 deletions libreforms_fastapi/app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4731,43 +4731,6 @@ def build_ui_context():

return kwargs

# Create form
@app.get("/ui/form/create/{form_name}", response_class=HTMLResponse, include_in_schema=False)
@requires(['authenticated'], redirect="ui_auth_login")
async def ui_form_create(form_name:str, request: Request, config = Depends(get_config_depends), doc_db = Depends(get_doc_db), session: SessionLocal = Depends(get_db)):
if not config.UI_ENABLED:
raise HTTPException(status_code=404, detail="This page does not exist")

if form_name not in get_form_names(config_path=config.FORM_CONFIG_PATH):
raise HTTPException(status_code=404, detail=f"Form '{form_name}' not found")

_context = {
'user': request.user.to_dict(),
'config': config.model_dump()
}

# generate_html_form
form_html = get_form_html(
form_name=form_name,
config_path=config.FORM_CONFIG_PATH,
session=session,
User=User,
Group=Group,
doc_db=doc_db,
context=_context,
)

return templates.TemplateResponse(
request=request,
name="create_form.html.jinja",
context={
"form_name": form_name,
"form_html": form_html,
**build_ui_context(),
}
)



# Read one form
@app.get("/ui/form/read_one/{form_name}/{document_id}", response_class=HTMLResponse, include_in_schema=False)
Expand Down Expand Up @@ -4860,6 +4823,44 @@ async def ui_form_read_all(request: Request, config = Depends(get_config_depends
}
)



# Create form
@app.get("/ui/form/create/{form_name}", response_class=HTMLResponse, include_in_schema=False)
@requires(['authenticated'], redirect="ui_auth_login")
async def ui_form_create(form_name:str, request: Request, config = Depends(get_config_depends), doc_db = Depends(get_doc_db), session: SessionLocal = Depends(get_db)):
if not config.UI_ENABLED:
raise HTTPException(status_code=404, detail="This page does not exist")

if form_name not in get_form_names(config_path=config.FORM_CONFIG_PATH):
raise HTTPException(status_code=404, detail=f"Form '{form_name}' not found")

_context = {
'user': request.user.to_dict(),
'config': config.model_dump()
}

# generate_html_form
form_html = get_form_html(
form_name=form_name,
config_path=config.FORM_CONFIG_PATH,
session=session,
User=User,
Group=Group,
doc_db=doc_db,
context=_context,
)

return templates.TemplateResponse(
request=request,
name="create_form.html.jinja",
context={
"form_name": form_name,
"form_html": form_html,
**build_ui_context(),
}
)

# Update form
@app.get("/ui/form/update/{form_name}/{document_id}", response_class=HTMLResponse, include_in_schema=False)
@requires(['authenticated'], redirect="ui_auth_login")
Expand Down Expand Up @@ -4918,7 +4919,7 @@ async def ui_form_duplicate(form_name:str, document_id:str, request: Request, co
form_html = get_form_html(
form_name=form_name,
config_path=config.FORM_CONFIG_PATH,
update=True,
duplicate=True,
session=session,
User=User,
Group=Group,
Expand Down
2 changes: 1 addition & 1 deletion libreforms_fastapi/app/static/js/custom.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ function renderUserRelationships(users) {


function prettifyTimeDiff(dateTimeStr, tz="America/New_York") {
console.log(dateTimeStr);
// console.log(dateTimeStr);

// Parse the date string into a Date object
// const date = new Date(dateTimeStr);
Expand Down
15 changes: 14 additions & 1 deletion libreforms_fastapi/app/templates/duplicate_form.html.jinja
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{% extends "base.html.jinja" %}

{% block title %}
{{ config.SITE_NAME }} — Update Form
{{ config.SITE_NAME }} — Duplicate Form
{% endblock %}

{% block content %}
Expand Down Expand Up @@ -169,10 +169,23 @@ $(document).ready(function() {
// Populate form fields with fetched data
function populateFormData(response) {
const data = response.data;
for (const key in data) {
const value = data[key];
const field = $(`[name="${key}"]`);
// Check if the field has the data-mutable attribute and if it's set to "true"
const isMutable = field.attr('data-mutable') === 'true';
// Debugging: Log field information
console.log(`Field: ${key}, Data Mutable: ${isMutable}`);
if (isMutable) {
// Skip setting the value for fields marked as mutable
console.log("Skipping mutable field: ", key);
continue;
}
if (Array.isArray(value)) {
// For checkboxes or multi-selects
value.forEach(val => {
Expand Down
8 changes: 7 additions & 1 deletion libreforms_fastapi/app/templates/update_form.html.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -175,12 +175,18 @@ $(document).ready(function() {
function populateFormData(response) {
const data = response.data;
console.log(data);
// console.log(data);
for (const key in data) {
const value = data[key];
const field = $(`[name="${key}"]`);
if (field.attr('data-mutable') === 'true') {
// Skip setting the value for fields marked as mutable
console.log("Data Mutable: ", key);
continue;
}
if (Array.isArray(value)) {
// For checkboxes or multi-selects
value.forEach(val => {
Expand Down
19 changes: 14 additions & 5 deletions libreforms_fastapi/utils/pydantic_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -627,6 +627,7 @@ def get_form_html(
config_path: str | None = None,
current_document: dict | None = None,
update:bool = False,
duplicate:bool = False,
initialize_full_loader: bool = True,
doc_db = None,
session = None,
Expand Down Expand Up @@ -705,7 +706,7 @@ def get_form_html(
else:
default = field_info.get("default","")

if update:
if update or duplicate:
default = ""

# if not default: # "" has a False-like truth value
Expand Down Expand Up @@ -746,8 +747,17 @@ def get_form_html(
# This value will always be static and linked to a context variable like request.user or config.SITE_NAME
elif field_info['input_type'] == "immutable_context":

# Start by pulling the context field and splitting on the period. These support user.<some_attr> and
# config.<some_attr>.
if update:
make_mutable = field_info.get('update_on_edit', False)
elif duplicate:
make_mutable = field_info.get('update_on_duplicate', True)
else:
make_mutable = False

mutable_attr = 'data-mutable="true"' if make_mutable else 'data-mutable="false"'

# Start by pulling the context field and splitting on the period. These support
# user.<some_attr> and config.<some_attr>.
_context_field = field_info.get('context_field', '')
_expanded_context = _context_field.split('.')

Expand All @@ -757,12 +767,11 @@ def get_form_html(
if isinstance(_value, dict):
_value = _value.get(layer, "")


field_html += f'''
<fieldset class="form-check" style=" padding-top: 20px;">
<label aria-labelledby="{description_id}" for="{field_name}" class="form-check-label">{visible_field_name}</label>
<span id="{description_id}" class="form-text"> {' Required.' if required else ''} {description_text} {tooltip_text}</span>
<input type="text" readonly class="form-control" id="{field_name}"
<input type="text" readonly class="form-control" id="{field_name}" {mutable_attr}
name="{field_name}" {field_params}
value="{_value}">
</fieldset>'''
Expand Down

0 comments on commit 707594f

Please sign in to comment.