Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: wrong label to belongs_to #2762

Merged
merged 4 commits into from
May 16, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/components/avo/field_wrapper_component.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"md:w-64": !compact?,
}), data: {slot: "label"} do %>
<% if form.present? %>
<%= form.label field.form_field_label, label %>
<%= form.label label_for, label %>
<% else %>
<%= field.name %>
<% end %>
Expand Down
6 changes: 6 additions & 0 deletions app/components/avo/field_wrapper_component.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ def initialize(
stacked: nil,
style: "",
view: :show,
label_for: nil,
**args
)
@args = args
Expand All @@ -43,6 +44,7 @@ def initialize(
@stacked = stacked
@style = style
@view = view
@label_for = label_for
end

def classes(extra_classes = "")
Expand All @@ -57,6 +59,10 @@ def label
@label || @field.name
end

def label_for
@label_for || @field.form_field_label
end

delegate :show?, :edit?, to: :view, prefix: :on

def help
Expand Down
100 changes: 50 additions & 50 deletions app/components/avo/fields/belongs_to_field/edit_component.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
data-association="<%= @field.id %>"
data-association-class="<%= @field&.target_resource&.model_class || nil %>"
>
<%= field_wrapper **field_wrapper_args, help: @field.polymorphic_help || '' do %>
<%= field_wrapper **field_wrapper_args, label_for: @field.polymorphic_form_field_label, help: @field.polymorphic_help || '' do %>
<%= @form.select @field.type_input_foreign_key, @field.types.map { |type| [Avo.resource_manager.get_resource_by_model_class(type.to_s).name, type.to_s] },
{
value: @field.value,
Expand All @@ -28,59 +28,59 @@
<%= @form.hidden_field @field.type_input_foreign_key %>
<% end %>
<% end %>
<div data-belongs-to-field-target="container"></div>
<% @field.types.each do |type| %>
<div class="hidden"
data-belongs-to-field-target="type"
data-type="<%= type %>"
>
<%= field_wrapper **field_wrapper_args.merge!(data: reload_data), label: Avo.resource_manager.get_resource_by_model_class(type.to_s).name do %>
<% if @field.is_searchable? %>
<%= render Avo::Pro::SearchableAssociations::AutocompleteComponent.new form: @form,
disabled: disabled,
field: @field,
foreign_key: @field.id_input_foreign_key,
model_key: model_keys[type.to_s],
polymorphic_record: polymorphic_record,
resource: @resource,
style: @field.get_html(:style, view: view, element: :input),
type: type,
classes: classes("w-full"),
view: view
%>
<% else %>
<%= @form.select @field.id_input_foreign_key,
options_for_select(@field.values_for_type(type), @resource.present? && @resource.record.present? ? @resource.record[@field.id_input_foreign_key] : nil),
{
value: @resource.record[@field.id_input_foreign_key].to_s,
include_blank: @field.placeholder,
},
{
class: classes("w-full"),
data: @field.get_html(:data, view: view, element: :input),
disabled: disabled
}
%>
<%
# If the select field is disabled, no value will be sent. It's how HTML works.
# Thus the extra hidden field to actually send the related id to the server.
if disabled %>
<%= @form.hidden_field @field.id_input_foreign_key %>
<template data-belongs-to-field-target="type" data-type="<%= type %>">
<div>
<%= field_wrapper **field_wrapper_args.merge!(data: reload_data), label: Avo.resource_manager.get_resource_by_model_class(type.to_s).name do %>
<% if @field.is_searchable? %>
<%= render Avo::Pro::SearchableAssociations::AutocompleteComponent.new form: @form,
disabled: disabled,
field: @field,
foreign_key: @field.id_input_foreign_key,
model_key: model_keys[type.to_s],
polymorphic_record: polymorphic_record,
resource: @resource,
style: @field.get_html(:style, view: view, element: :input),
type: type,
classes: classes("w-full"),
view: view
%>
<% else %>
<%= @form.select @field.id_input_foreign_key,
options_for_select(@field.values_for_type(type), @resource.present? && @resource.record.present? ? @resource.record[@field.id_input_foreign_key] : nil),
{
value: @resource.record[@field.id_input_foreign_key].to_s,
include_blank: @field.placeholder,
},
{
class: classes("w-full"),
data: @field.get_html(:data, view: view, element: :input),
disabled: disabled
}
%>
<%
# If the select field is disabled, no value will be sent. It's how HTML works.
# Thus the extra hidden field to actually send the related id to the server.
if disabled %>
<%= @form.hidden_field @field.id_input_foreign_key %>
<% end %>
<% end %>
<% end %>
<% if field.can_create? %>
<% create_href = create_path(Avo.resource_manager.get_resource_by_model_class(type.to_s)) %>
<% if !disabled && create_href.present? %>
<%= link_to t("avo.create_new_item", item: type.model_name.human.downcase),
create_href,
class: "text-sm",
data: {
turbo_prefetch: false
}
%>
<% if field.can_create? %>
<% create_href = create_path(Avo.resource_manager.get_resource_by_model_class(type.to_s)) %>
<% if !disabled && create_href.present? %>
<%= link_to t("avo.create_new_item", item: type.model_name.human.downcase),
create_href,
class: "text-sm",
data: {
turbo_prefetch: false
}
%>
<% end %>
<% end %>
<% end %>
<% end %>
</div>
</div>
</template>
<% end %>
</div>
<% else %>
Expand Down
127 changes: 8 additions & 119 deletions app/javascript/js/controllers/fields/belongs_to_field_controller.js
Original file line number Diff line number Diff line change
@@ -1,136 +1,25 @@
import { Controller } from '@hotwired/stimulus'

export default class extends Controller {
static targets = ['select', 'type', 'loadAssociationLink'];

defaults = {};

get selectedType() {
return this.selectTarget.value
}

get isSearchable() {
return this.context.scope.element.dataset.searchable === 'true'
}

get association() {
return this.context.scope.element.dataset.association
}

get associationClass() {
return this.context.scope.element.dataset.associationClass
}
static targets = ['select', 'type', 'container']

connect() {
this.copyValidNames()
this.changeType() // Do the initial type change
}

changeType() {
this.hideAllTypes()
this.showType(this.selectTarget.value)
this.#hideAllTypes()
this.#showType(this.selectTarget.value)
}

// Private

hideAllTypes() {
this.typeTargets.forEach((target) => {
target.classList.add('hidden')

this.invalidateTarget(target)
})
#hideAllTypes() {
this.containerTarget.innerHTML = ''
}

/**
* Used for invalidating select fields when switching between types so they don't automatically override the previous id.
* Ex: There are two types Article and Project and the Comment has commentable_id 3 and commentable_type: Article
* When you change the type from Project to Article the Project field will override the commentable_id value
* because it was rendered later (alphabetical sorting) and the browser will pick that one up.
* So we go and copy the name attribute to valid-name for all types and then copy it back to name when the user selects it.
*/

/**
* This method does the initial copying from name to valid-name.
*/
copyValidNames() {
this.typeTargets.forEach((target) => {
const { type } = target.dataset

if (this.isSearchable) {
const textInput = target.querySelector('input[type="text"]')
if (textInput) this.nameToValidName(textInput)

const hiddenInput = target.querySelector('input[type="hidden"]')
if (hiddenInput) this.nameToValidName(hiddenInput)
} else {
const select = target.querySelector('select')
if (select) this.nameToValidName(select)

const hiddenInput = target.querySelector('input[type="hidden"]')
if (hiddenInput) this.nameToValidName(hiddenInput)

if (this.selectedType !== type) {
select.selectedIndex = 0
}
}
})
}

showType(type) {
const target = this.typeTargets.find(
(typeTarget) => typeTarget.dataset.type === type,
)
#showType(type) {
const target = this.typeTargets.find((typeTarget) => typeTarget.dataset.type === type)
if (target) {
target.classList.remove('hidden')

this.validateTarget(target)
}
}

/**
* Copy value from `valid-name` to `name`
*/
validateTarget(target) {
if (this.isSearchable) {
const textInput = target.querySelector('input[type="text"]')
const hiddenInput = target.querySelector('input[type="hidden"]')

this.validNameToName(textInput)
this.validNameToName(hiddenInput)
} else {
const select = target.querySelector('select')
const hiddenInput = target.querySelector('input[type="hidden"]')
this.validNameToName(select)

if (hiddenInput) {
this.validNameToName(hiddenInput)
}
this.containerTarget.appendChild(target.content)
}
}
Paul-Bob marked this conversation as resolved.
Show resolved Hide resolved

/**
* nullify the `name` attribute
*/
invalidateTarget(target) {
if (this.isSearchable) {
// Wrapping it in a try/catch to counter turbo's cache system (going back to the edit page after initial save)
try {
target.querySelector('input[type="text"]').setAttribute('name', '')
target.querySelector('input[type="hidden"]').setAttribute('name', '')
} catch {}
} else if (target) {
try {
target.querySelector('select').setAttribute('name', '')
target.querySelector('input[type="hidden"]').setAttribute('name', '')
} catch (error) {}
}
}

validNameToName(target) {
target.setAttribute('name', target.getAttribute('valid-name'))
}

nameToValidName(target) {
target.setAttribute('valid-name', target.getAttribute('name'))
}
}
6 changes: 5 additions & 1 deletion lib/avo/fields/belongs_to_field.rb
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,11 @@ def can_create?
end

def form_field_label
id
"#{id}_id"
end

def polymorphic_form_field_label
"#{id}_type"
end

private
Expand Down
2 changes: 1 addition & 1 deletion spec/dummy/config/initializers/money.rb
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@
#
# For the legacy behaviour of "per currency" localization (formatting depends
# only on currency):
# config.locale_backend = :currency
config.locale_backend = :currency
#
# Example:
# Money.new(10_000_00, 'USD').format # => $10,000.00
Expand Down