Skip to content

Instantly share code, notes, and snippets.

@jdltechworks
Last active July 11, 2020 23:57
Show Gist options
  • Save jdltechworks/857baa67bf0ce42556bf8ae99cf0dc81 to your computer and use it in GitHub Desktop.
Save jdltechworks/857baa67bf0ce42556bf8ae99cf0dc81 to your computer and use it in GitHub Desktop.
import map from 'lodash/map'
import groupBy from 'lodash/groupBy'
import reduce from 'lodash/reduce'
import omit from 'lodash/omit'
function hookie () {
document.addEventListener('livewire:load', (event) => {
window.livewire.hook('afterDomUpdate', (component) => {
nestedValidationErrors(component.errorBag, event, component.id)
})
})
}
function nestedValidationErrors(errorBag, event, id) {
const mappedErrors = map(errorBag, (error, key) => {
const [model, index, nestedModel] = key.split('.')
const [message] = error
return { index: Number(index), [nestedModel]: message.replace(key, nestedModel) }
})
const errorGroup = groupBy(mappedErrors, 'index')
const errors = reduce(errorGroup, (acc, value, key) => {
let props = {}
value.forEach((val) => {
const prop = omit(val, ['index'])
props = {...props, ...prop}
})
acc[key] = {...props}
return acc
}, [])
const errorEvent = new CustomEvent('model-errors', {
trusted: true,
bubbles: true,
detail: { componentId: id, errors }
})
event.target.dispatchEvent(errorEvent)
}
export default hookie
import "alpinejs"
import './components/hookie'
import hookie from "./components/hookie"
(() => {
hookie()
})()
<div x-data="yourScript()" @model-errors.window="validationErrors">
<your-nested-form-code>
</div>
@push('scripts')
<script>
function yourScript() {
return {
//yours props,
validationErrors({ detail }) {
if (@this.id === detail.componentId) {
console.log(details.errors)
}
}
}
}
</script>
@endpush
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment