ASP.NET MVC Multiple File Uploads - asp.net-mvc-2

I'm working on a strongly-typed edit form for a MVC model that contains a collection of child models (Document contains many LocalizedDocuments). Each document can contain 0, 1, or many localized documents, and every localized document has an input type="file" to allow the user to upload a new version of the file.
To render the edit fields for each LocalizedDocument I have a strongly-typed partial view that contains the fields for the LocalizedDocument, and then in my edit view use Html.EditorFor(model => model.Document.LocalizedDocuments).
When the form is posted, each of my LocalizedDocument fields are prefixed with LocalizedDocument[i], as expected. However, how can I get it so the file input is also prefixed with LocalizedDocument[i], so I can relate the file upload to the appropriate LocalizedDocument?

Tell me if I'm interpreting this question wrong. You have documents that you need to upload that belongs to a parent table or you need to assign these documents a specific id after uploading multiple of them?
I'll be using Uploadify.
You will have to know the Id of the LocalizedDocument. You will also only be able to upload 1 at a time. (each file is a separate server call)
First you have to assign the Id of the LocalizedDocument to the data that will be sent to the server.
<script type="text/javascript">
var auth = "<%: Request.Cookies[FormsAuthentication.FormsCookieName]==null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value %>";
var ASPSESSID = "<%: Session.SessionID %>";
$(document).ready(function () {
$('#file_upload').uploadify({
'uploader': '/Content/uploadify.swf',
'script': '<%: Url.Action("Upload", "Documents") %>',
'cancelImg': '/Content/Images/cancel.png',
'folder': '/uploads',
'scriptData': { ASPSESSID: ASPSESSID, AUTHID: auth, DocumentId: <%: Model.LocalizedDocumentId %>},
'auto':true,
'multi': true
});
});
</script>
Controller:
public ActionResult InsertImages(HttpPostedFileBase FileData, int DocId){ }

Related

MongoDB pre save set field based on lookup logic

People register for an event. There are two collections in the database. One for new registrations coming in and one for the registrations of previous years. Both contain an email field as unique identifier.
I would like to know if its possible to check if a newly registered person has registered before in previous years. If so add a field, for example: returningCustomer: true. Otherwise add returningCustomer: false
I am using Mongoose and have a User model for new registrations. I don't have a model (yet) for previously registered users. Would that be neccesary? If it is possible to check if a person has registered before and a field can be added before saving, it might be handy to save the user to the returning customers collection immediatly as well.
I know it is possible to access the current document and collection using a pre save hook, but how about doing a lookup in another collection, write a bit of logic and add a field to the current document pre save?
userSchema.pre('save', function (doc, next) {
const exists = otherCollection.find({ email: doc.email });
exists ? doc.returningCustomer = true : doc.returningCustomer = false;
next();
});
You should have a model for the collection you want to lookup.
Then you can query the other collection before saving the current collection.
CurrentModel.pre('save', async function (next) {
const doc = await OtherModel.find({ field: this.field });
doc.length ? this.returningCustomer = false : this.returningCustomer = true;
next();
});

Support for resource nesting

I am wondering, is it possible to configure DataProvider/Resource/List to support REST urls like api/users/1/roles?
For RESTful API it is very common use case to get childs of certain parent entity, but I cant figure it how to setup React Admin and achieve this. I am using custom DataProvider build on OData spec backend.
I understand that I can get roles of certain user by filtered request on api/roles?filter={userId: 1} or something like that, but my issue is that my users and roles are in many-to-many relation so relation references are stored in pivot table. In other words, I dont have reference on user in roles table so I cant filter them.
Am I overseeing something or is there some approach which I simply dont see?
EDIT:
REST API is built in OData spec and it supports many-to-many relations with classic pivot (or intermediate) table. This table is not exposed in API, but is utilized in urls like the one above. So I cant directly access it as a resource.
Schema for User - Role relations looks pretty standard too.
|----------| |-----------| |--------|
| USER | | User_Role | | Role |
|----------| |-----------| |--------|
| Id |-\ | Id | /-| Id |
| Login | \-| UserId | / | Name |
| Password | | RoleId |-/ | Code |
|----------| |-----------| |--------|
TL;DR: By default, React Admin doesn't support nested resource, you have to write a custom data provider.
This question was answered on a past issue: maremelab/react-admin#261
Detailed Answer
The default data provider in React Admin is ra-data-simple-rest.
As explained on its documentation, this library doesn't support nested resources since it only use the resource name and the resource ID to build a resource URL:
In order to support nested resources, you have to write your own data provider.
Nested resources support is a recurrent feature request but, at the time, the core team don't want to handle this load of work.
I strongly suggest to gather your forces and write an external data provider and publish it like ra-data-odata provider. It would be a great addition and we will honored to help you with that external package.
Your question was already answer here, but I would like to tell you about my workaround in order for React-Admin work with many-to-many relations.
As said in the mentioned answer you have to extend the DataProvider in order for it to fetch resources of a many-to-many relation. However you need to use the new REST verb, lets suppose GET_MANY_MANY_REFERENCE somewhere on your application. Since different REST services/API can have different routes formats to fetch related resources I didn't bother trying to build a new DataProvider, I know is not a great solution, but for short deadlines is considerable simple.
My solution was taking inspiration on <ReferenceManyField> and build a new component <ReferenceManyManyField> for many-to-many relations. This component fetches related records on componentDidMount using fetch API. On response uses the response data to build to objects one data being an object with keys being record ids, and values the respective record object, and an ids array with the ids of records. This is passes to children along with other state variables like page, sort, perPage, total, to handle pagination and ordering of data. Be aware that changing the order of the data in a Datagrid means a new request will be made to the API. This component is divided in a controller and a view, like <ReferencemanyField>, where controller fetches data, manages it and passes it to children and view that receives controller data and passes it to children render its content. That made me possible to render many-to-many relations data on a Datagrid, even if with some limitation, is a component to aggregated to my project and only work with my current API if something changes I would have to change the field to, but as for now it works and can be reused along my app.
Implementation details go as follow:
//ReferenceManyManyField
export const ReferenceManyManyField = ({children, ...prop}) => {
if(React.Children.count(children) !== 1) {
throw new Error( '<ReferenceManyField> only accepts a single child (like <Datagrid>)' )
}
return <ReferenceManyManyFieldController {...props}>
{controllerProps => (<ReferenceManyManyFieldView
{...props}
{...{children, ...controllerProps}} /> )}
</ReferenceManyManyFieldController>
//ReferenceManyManyFieldController
class ReferenceManyManyFieldController extends Component {
constructor(props){
super(props)
//State to manage sorting and pagination, <ReferecemanyField> uses some props from react-redux
//I discarded react-redux for simplicity/control however in the final solution react-redux might be incorporated
this.state = {
sort: props.sort,
page: 1,
perPage: props.perPage,
total: 0
}
}
componentWillMount() {
this.fetchRelated()
}
//This could be a call to your custom dataProvider with a new REST verb
fetchRelated({ record, resource, reference, showNotification, fetchStart, fetchEnd } = this.props){
//fetchStart and fetchEnd are methods that signal an operation is being made and make active/deactivate loading indicator, dataProvider or sagas should do this
fetchStart()
dataProvider(GET_LIST,`${resource}/${record.id}/${reference}`,{
sort: this.state.sort,
pagination: {
page: this.state.page,
perPage: this.state.perPage
}
})
.then(response => {
const ids = []
const data = response.data.reduce((acc, record) => {
ids.push(record.id)
return {...acc, [record.id]: record}
}, {})
this.setState({data, ids, total:response.total})
})
.catch(e => {
console.error(e)
showNotification('ra.notification.http_error')
})
.finally(fetchEnd)
}
//Set methods are here to manage pagination and ordering,
//again <ReferenceManyField> uses react-redux to manage this
setSort = field => {
const order =
this.state.sort.field === field &&
this.state.sort.order === 'ASC'
? 'DESC'
: 'ASC';
this.setState({ sort: { field, order } }, this.fetchRelated);
};
setPage = page => this.setState({ page }, this.fetchRelated);
setPerPage = perPage => this.setState({ perPage }, this.fetchRelated);
render(){
const { resource, reference, children, basePath } = this.props
const { page, perPage, total } = this.state;
//Changed basePath to be reference name so in children can nest other resources, not sure why the use of replace, maybe to maintain plurals, don't remember
const referenceBasePath = basePath.replace(resource, reference);
return children({
currentSort: this.state.sort,
data: this.state.data,
ids: this.state.ids,
isLoading: typeof this.state.ids === 'undefined',
page,
perPage,
referenceBasePath,
setPage: this.setPage,
setPerPage: this.setPerPage,
setSort: this.setSort,
total
})
}
}
ReferenceManyManyFieldController.defaultProps = {
perPage: 25,
sort: {field: 'id', order: 'DESC'}
}
//ReferenceManyManyFieldView
export const ReferenceManyManyFieldView = ({
children,
classes = {},
className,
currentSort,
data,
ids,
isLoading,
page,
pagination,
perPage,
reference,
referenceBasePath,
setPerPage,
setPage,
setSort,
total
}) => (
isLoading ?
<LinearProgress className={classes.progress} />
:
<Fragment>
{React.cloneElement(children, {
className,
resource: reference,
ids,
data,
basePath: referenceBasePath,
currentSort,
setSort,
total
})}
{pagination && React.cloneElement(pagination, {
page,
perPage,
setPage,
setPerPage,
total
})}
</Fragment>
);
//Assuming the question example, the presentation of many-to-many relationship would be something like
const UserShow = ({...props}) => (
<Show {...props}>
<TabbedShowLayout>
<Tab label='User Roles'>
<ReferenceManyManyField source='users' reference='roles' addLabel={false} pagination={<Pagination/>}>
<Datagrid>
<TextField source='name'/>
<TextField source='code'/>
</Datagrid>
</ReferenceManyManyField>
</Tab>
</TabbedShowLayout>
</Show>
)
//Used <TabbedShowLayout> because is what I use in my project, not sure if works under <Show> or <SimpleShowLayout>, but I think it work since I use it in other contexts
I think the implementation can be improved and be more compatible with React-Admin. In other reference fields data fetch is stored on react-redux state, in this implementation it's not. The relation is not saved anywhere besides the component making application not work on offline since can't fetch data, not even ordering is possible.
Had a very similar question. My solution was more of a hack but a little simpler to implement if all you want is to enable a ReferenceManyField. Only the dataProvider needs to be modified:
I'm repeating my solution here modified for the current question:
Using the stock ReferenceManyField:
<Show {...props}>
<TabbedShowLayout>
<Tab label="Roles">
<ReferenceManyField reference="roles" target="_nested_users_id" pagination={<Pagination/>} >
<Datagrid>
<TextField source="role" />
</Datagrid>
</ReferenceManyField>
</Tab>
</TabbedShowLayout>
</Show>
I then modified my dataProvider, which is a fork of ra-jsonapi-client.
I changed index.js under the case GET_MANY_REFERENCE from this:
// Add the reference id to the filter params.
query[`filter[${params.target}]`] = params.id;
url = `${apiUrl}/${resource}?${stringify(query)}`;
to this:
// Add the reference id to the filter params.
let refResource;
const match = /_nested_(.*)_id/g.exec(params.target);
if (match != null) {
refResource = `${match[1]}/${params.id}/${resource}`;
} else {
query[`filter[${params.target}]`] = params.id;
refResource = resource;
}
url = `${apiUrl}/${refResource}?${stringify(query)}`;
So basically I just remap the parameters to the url for the special case where the target matches a hard coded regex.
ReferenceManyField would normally have caused the dataProvider to call api/roles?filter[_nested_users_id]=1 and this modification makes the dataProvider call api/users/1/roles instead. It is transparent to react-admin.
Not elegant but it works and doesn't seem to break anything on the front end.

Wordpress GravityForm autosubmit with a parameter

I have a requirement to auto-submit a GravityForm with a form parameter. So, as far as I know GravityForms has the ability for you to send a parameter through the URL and it'll automatically fill out a field for you. What I want to do is the ability to send another field called autosubmit=true in which if that is on there, it will automatically submit the form.
Here is a generic solution for any form: Automatically submit a form
And here is a Gravity Forms specific solution: https://www.gravityhelp.com/forums/topic/autosubmit-with-gravity-forms
The basic premise of both is that you use Javascript to trigger the form submission when the page loads. You would need to make yours conditional so that it checks the value of your pre-populated autosubmit field.
<script>
jQuery( document ).ready( function() {
// Update "1" to your form ID and "2" to your prepop field ID
if( jQuery( '#input_1_2' ) == 1 ) {
// Update "1" to your form ID
jQuery( 'form#gform_1' ).trigger( 'submit' );
}
} );
</script>

How to retrieve only part of a document back in a call

I need to retrieve only part of a document and call it via a helper so that I can render a subtemplate multiple times as the part I require to pull from the db is an array of object itself. I have the following as the fields. What I need to do with my helper is only retrieve the ordersDispatch array of one particular document which would be uniquely called by the tripNumber field.
I have tried several things but nothing has come close to only having an array of the objects in the orderDisptach field be returned in a fashion that it can be used by the helper to render my subtemplate for each object in the array.
{
tripNumber: companyRecord.lastTripNum + 1,
custID: $('input:hidden[name=orderCustomerId]').val(),
custContact: $('input:text[name=customerContact]').val(),
custEmail: $('input:text[name=customerEmail]').val(),
trailerSealNum: $('input:text[name=trailerSealNum]').val(),
orderBroker: $('input:text[name=orderBroker]').val(),
orderEquipment: $('input:text[name=orderEquipment]').val(),
orderLoadNum: $('input:text[name=orderLoadNum]').val(),
orderPlacedDate: $('input:text[name=orderPlacedDate]').val(),
orderPrivateNotes: $('textarea[name=orderPrivateNotes]').val(),
orderPublicNotes: $('textarea[name=orderPublicNotes]').val(),
orderCurrency: $("input[name=orderCurrency]:checked").val(),
orderCharges: $('input:text[name=orderCharges]').val(),
orderFUELCheck: $('input:checkbox[name=orderFUELCheck]').is(':checked'),
orderFUELPerc: $('input:text[name=orderFUELPerc]').val(),
orderFUELTotal: $('input:text[name=orderFUELTotal]').val(),
orderGSTCheck: $('input:checkbox[name=orderGSTCheck]').is(':checked'),
orderGSTPerc: $('input:text[name=orderGSTPerc]').val(),
orderGSTTotal: $('input:text[name=orderGSTTotal]').val(),
orderPSTCheck: $('input:checkbox[name=orderPSTCheck]').is(':checked'),
orderPSTPerc: $('input:text[name=orderPSTPerc]').val(),
orderPSTTotal: $('input:text[name=orderPSTTotal]').val(),
orderTAXCheck: $('input:checkbox[name=orderTAXCheck]').is(':checked'),
orderTAXPerc: $('input:text[name=orderTAXPerc]').val(),
orderTAXTotal: $('input:text[name=orderTAXTotal]').val(),
orderTotalCharges: $('input:text[name=orderTotalCharges]').val(),
ordeBlockInvoicing: $('input:checkbox[name=ordeBlockInvoicing]').is(':checked'),
orderExtraCharges: orderExtraCharges,
orderPickups: puLocations,
orderDeliveries: delLocations,
orderDispatch: dispatchLocations,
createdDate: new Date(),
createdUser: currentUser.username
Any help in building a helper that will accomplish this would be greatly appreciated as I am new to meteor and mongo.
The following helper should give you what you need:
Template.oneTrip.helpers({
orderDispatch: function(tn){
return Trips.findOne({ tripNumber: tn }).orderDispatch;
}
});
Trips.findOne({ tripNumber: tn }) gets you an individual document and .orderDispatch returns the value of the orderDispatch key which in your case will be an array.
html:
<template name="oneTrip">
{{#each orderDispatch this._id}} <!-- assuming you've already set the data context to an individual order -->
{{this}} <!-- now the data context is an element of the orderDispatch array -->
{{/each}}
</template>

Grails Searchable Plugin for multiple domain classes and multiple search fields with a single submit button

I have multiple domain objects and having one to many, many to many relationships and search data comes from couple of tables and it is always same. I implemented Searchable plugin in my app and able to retrieve results when I have single search field like this:
<g:form url='[controller: "searchable", action: "searchContact"]' id="searchableForm" name="searchableForm" method="get">
<g:textField name="query" value="${params.query}" size="40"/>
<input type="submit" value="Search Contact" />
</g:form>.
But I have multiple text fields, check boxes and g:select boxes to get searchTerm. Based on any one of fields or multiple search selections I have to get search results. How to include all search fields in between and having a single submit button for all the params. Here is my search action code:
def searchContact = {
if (!params.query) {
return [:]
}
try {
String searchTerm = params.query
println searchTerm
return [searchResult: searchableService.search(searchTerm, params)]
} catch (SearchEngineQueryParseException ex) {
return [parseException: true]
}
}
Quick suggestions are appreciated.
You can pass all the terms in one String query separating each token/word by a space, so for example if you have two Domain classes one called Person and another one called Job and you search for "John" and "Engineer", your String query should be "John Engineer" and that should get you both domain objects.
Is that kind of what you are looking for?