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

Storage Manager Form Overrides Not Working #970

Closed
4 tasks done
ErikCH opened this issue Jun 6, 2023 · 4 comments
Closed
4 tasks done

Storage Manager Form Overrides Not Working #970

ErikCH opened this issue Jun 6, 2023 · 4 comments
Labels
bug An issue which has been identified as a bug studio-ui An issue that needs to be tracked by Studio Console team ui-forms issues related to UI builder forms

Comments

@ErikCH
Copy link

ErikCH commented Jun 6, 2023

Before opening, please confirm:

App Id

d1cly8e6g4zmba

Region

us-east-1

Environment name

storage-ex

Figma File Version (if applicable)

No response

Amplify CLI Version

12.0.3

If applicable, what version of Node.js are you using?

v16.15.0

What operating system are you using?

Mac

Browser type?

Google

Describe the bug

I added the Storage Manager as a new field (not connected to an existing field), but after I pull it down into my app, all the overrides for it do not work, when I override it for the form that was created.

I also tried adding StorageField to an existing field, and the overrides still didn't work.

Expected behavior

It should allow you to override the props for Storage Manager.

Reproduction steps

Steps to reproduce.

  1. Create a studio app with Data, Auth, and Storage
  2. In side UI Library go into a create form, and add a new Storage Field.
  3. Pull into app
  4. Inside main file, use overrides to update the processFile
  <CabinCreateForm
        overrides={{
          Field0: {
            processFile(event) {
              console.log("event", event);
              return event;
            },
          },
        }}
      />

Nothing happens during process file. No other props can be overriden either.

Project Identifier

No response

Additional information

No response

@ErikCH ErikCH added the pending-triage An issue that is pending triage label Jun 6, 2023
@ErikCH ErikCH changed the title Storage Manager Overrides Not Working Storage Manager Form Overrides Not Working Jun 6, 2023
@ErikCH
Copy link
Author

ErikCH commented Jun 6, 2023

Here is the full code for the CabinCreateForm.jsx file

/***************************************************************************
 * The contents of this file were generated with Amplify Studio.           *
 * Please refrain from making any modifications to this file.              *
 * Any changes to this file will be overwritten when running amplify pull. *
 **************************************************************************/

/* eslint-disable */
import * as React from "react";
import { Button, Flex, Grid, TextField } from "@aws-amplify/ui-react";
import { StorageManager } from "@aws-amplify/ui-react-storage";
import { Field, getOverrideProps } from "@aws-amplify/ui-react/internal";
import { Cabin } from "../models";
import { fetchByPath, processFile, validateField } from "./utils";
import { DataStore } from "aws-amplify";
export default function CabinCreateForm(props) {
  const {
    clearOnSuccess = true,
    onSuccess,
    onError,
    onSubmit,
    onValidate,
    onChange,
    overrides,
    ...rest
  } = props;
  const initialValues = {
    title: "",
    description: "",
    fileName: "",
    Field0: undefined,
  };
  const [title, setTitle] = React.useState(initialValues.title);
  const [description, setDescription] = React.useState(
    initialValues.description
  );
  const [fileName, setFileName] = React.useState(initialValues.fileName);
  const [Field0, setField0] = React.useState(initialValues.Field0);
  const [errors, setErrors] = React.useState({});
  const resetStateValues = () => {
    setTitle(initialValues.title);
    setDescription(initialValues.description);
    setFileName(initialValues.fileName);
    setField0(initialValues.Field0);
    setErrors({});
  };
  const validations = {
    title: [],
    description: [],
    fileName: [],
    Field0: [{ type: "Required" }],
  };
  const runValidationTasks = async (
    fieldName,
    currentValue,
    getDisplayValue
  ) => {
    const value =
      currentValue && getDisplayValue
        ? getDisplayValue(currentValue)
        : currentValue;
    let validationResponse = validateField(value, validations[fieldName]);
    const customValidator = fetchByPath(onValidate, fieldName);
    if (customValidator) {
      validationResponse = await customValidator(value, validationResponse);
    }
    setErrors((errors) => ({ ...errors, [fieldName]: validationResponse }));
    return validationResponse;
  };
  return (
    <Grid
      as="form"
      rowGap="15px"
      columnGap="15px"
      padding="20px"
      onSubmit={async (event) => {
        event.preventDefault();
        let modelFields = {
          title,
          description,
          fileName,
          Field0,
        };
        const validationResponses = await Promise.all(
          Object.keys(validations).reduce((promises, fieldName) => {
            if (Array.isArray(modelFields[fieldName])) {
              promises.push(
                ...modelFields[fieldName].map((item) =>
                  runValidationTasks(fieldName, item)
                )
              );
              return promises;
            }
            promises.push(
              runValidationTasks(fieldName, modelFields[fieldName])
            );
            return promises;
          }, [])
        );
        if (validationResponses.some((r) => r.hasError)) {
          return;
        }
        if (onSubmit) {
          modelFields = onSubmit(modelFields);
        }
        try {
          Object.entries(modelFields).forEach(([key, value]) => {
            if (typeof value === "string" && value.trim() === "") {
              modelFields[key] = undefined;
            }
          });
          const modelFieldsToSave = {
            title: modelFields.title,
            description: modelFields.description,
            fileName: modelFields.fileName,
          };
          await DataStore.save(new Cabin(modelFieldsToSave));
          if (onSuccess) {
            onSuccess(modelFields);
          }
          if (clearOnSuccess) {
            resetStateValues();
          }
        } catch (err) {
          if (onError) {
            onError(modelFields, err.message);
          }
        }
      }}
      {...getOverrideProps(overrides, "CabinCreateForm")}
      {...rest}
    >
      <TextField
        label="Title"
        isRequired={false}
        isReadOnly={false}
        value={title}
        onChange={(e) => {
          let { value } = e.target;
          if (onChange) {
            const modelFields = {
              title: value,
              description,
              fileName,
              Field0,
            };
            const result = onChange(modelFields);
            value = result?.title ?? value;
          }
          if (errors.title?.hasError) {
            runValidationTasks("title", value);
          }
          setTitle(value);
        }}
        onBlur={() => runValidationTasks("title", title)}
        errorMessage={errors.title?.errorMessage}
        hasError={errors.title?.hasError}
        {...getOverrideProps(overrides, "title")}
      ></TextField>
      <TextField
        label="Description"
        isRequired={false}
        isReadOnly={false}
        value={description}
        onChange={(e) => {
          let { value } = e.target;
          if (onChange) {
            const modelFields = {
              title,
              description: value,
              fileName,
              Field0,
            };
            const result = onChange(modelFields);
            value = result?.description ?? value;
          }
          if (errors.description?.hasError) {
            runValidationTasks("description", value);
          }
          setDescription(value);
        }}
        onBlur={() => runValidationTasks("description", description)}
        errorMessage={errors.description?.errorMessage}
        hasError={errors.description?.hasError}
        {...getOverrideProps(overrides, "description")}
      ></TextField>
      <TextField
        label="File name"
        isRequired={false}
        isReadOnly={false}
        value={fileName}
        onChange={(e) => {
          let { value } = e.target;
          if (onChange) {
            const modelFields = {
              title,
              description,
              fileName: value,
              Field0,
            };
            const result = onChange(modelFields);
            value = result?.fileName ?? value;
          }
          if (errors.fileName?.hasError) {
            runValidationTasks("fileName", value);
          }
          setFileName(value);
        }}
        onBlur={() => runValidationTasks("fileName", fileName)}
        errorMessage={errors.fileName?.errorMessage}
        hasError={errors.fileName?.hasError}
        {...getOverrideProps(overrides, "fileName")}
      ></TextField>
      <Field
        errorMessage={errors.Field0?.errorMessage}
        hasError={errors.Field0?.hasError}
        label={"Label"}
        isRequired={true}
      >
        <StorageManager
          onUploadSuccess={({ key }) => {
            setField0((prev) => {
              let value = key;
              if (onChange) {
                const modelFields = {
                  title,
                  description,
                  fileName,
                  Field0: value,
                };
                const result = onChange(modelFields);
                value = result?.Field0 ?? value;
              }
              return value;
            });
          }}
          onFileRemove={({ key }) => {
            setField0((prev) => {
              let value = initialValues?.Field0;
              if (onChange) {
                const modelFields = {
                  title,
                  description,
                  fileName,
                  Field0: value,
                };
                const result = onChange(modelFields);
                value = result?.Field0 ?? value;
              }
              return value;
            });
          }}
          processFile={processFile}
          accessLevel={"private"}
          acceptedFileTypes={[]}
          isResumable={false}
          showThumbnails={true}
          maxFileCount={1}
        ></StorageManager>
      </Field>
      <Flex
        justifyContent="space-between"
        {...getOverrideProps(overrides, "CTAFlex")}
      >
        <Button
          children="Clear"
          type="reset"
          onClick={(event) => {
            event.preventDefault();
            resetStateValues();
          }}
          {...getOverrideProps(overrides, "ClearButton")}
        ></Button>
        <Flex
          gap="15px"
          {...getOverrideProps(overrides, "RightAlignCTASubFlex")}
        >
          <Button
            children="Submit"
            type="submit"
            variation="primary"
            isDisabled={Object.values(errors).some((e) => e?.hasError)}
            {...getOverrideProps(overrides, "SubmitButton")}
          ></Button>
        </Flex>
      </Flex>
    </Grid>
  );
}

And the CabinCreeateForm.d.ts

/***************************************************************************
 * The contents of this file were generated with Amplify Studio.           *
 * Please refrain from making any modifications to this file.              *
 * Any changes to this file will be overwritten when running amplify pull. *
 **************************************************************************/

import * as React from "react";
import { GridProps, TextFieldProps } from "@aws-amplify/ui-react";
import { StorageManagerProps } from "@aws-amplify/ui-react-storage";
import { EscapeHatchProps } from "@aws-amplify/ui-react/internal";
export declare type ValidationResponse = {
    hasError: boolean;
    errorMessage?: string;
};
export declare type ValidationFunction<T> = (value: T, validationResponse: ValidationResponse) => ValidationResponse | Promise<ValidationResponse>;
export declare type CabinCreateFormInputValues = {
    title?: string;
    description?: string;
    fileName?: string;
    Field0?: string;
};
export declare type CabinCreateFormValidationValues = {
    title?: ValidationFunction<string>;
    description?: ValidationFunction<string>;
    fileName?: ValidationFunction<string>;
    Field0?: ValidationFunction<string>;
};
export declare type PrimitiveOverrideProps<T> = Partial<T> & React.DOMAttributes<HTMLDivElement>;
export declare type CabinCreateFormOverridesProps = {
    CabinCreateFormGrid?: PrimitiveOverrideProps<GridProps>;
    title?: PrimitiveOverrideProps<TextFieldProps>;
    description?: PrimitiveOverrideProps<TextFieldProps>;
    fileName?: PrimitiveOverrideProps<TextFieldProps>;
    Field0?: PrimitiveOverrideProps<StorageManagerProps>;
} & EscapeHatchProps;
export declare type CabinCreateFormProps = React.PropsWithChildren<{
    overrides?: CabinCreateFormOverridesProps | undefined | null;
} & {
    clearOnSuccess?: boolean;
    onSubmit?: (fields: CabinCreateFormInputValues) => CabinCreateFormInputValues;
    onSuccess?: (fields: CabinCreateFormInputValues) => void;
    onError?: (fields: CabinCreateFormInputValues, errorMessage: string) => void;
    onChange?: (fields: CabinCreateFormInputValues) => CabinCreateFormInputValues;
    onValidate?: CabinCreateFormValidationValues;
} & React.CSSProperties>;
export default function CabinCreateForm(props: CabinCreateFormProps): React.ReactElement;

@bombguy
Copy link

bombguy commented Jun 6, 2023

Codegen fix to render the override props to StorageManager is in PR. Will update when fix is merged in.
aws-amplify/amplify-codegen-ui#1020

@ykethan ykethan added bug An issue which has been identified as a bug studio-ui An issue that needs to be tracked by Studio Console team ui-forms issues related to UI builder forms and removed pending-triage An issue that is pending triage labels Jun 7, 2023
@cwoolum
Copy link
Contributor

cwoolum commented May 6, 2024

This has been resolved. Please re-open if you still are running into problems.

@cwoolum cwoolum closed this as completed May 6, 2024
Copy link

github-actions bot commented May 6, 2024

⚠️COMMENT VISIBILITY WARNING⚠️

Comments on closed issues are hard for our team to see.
If you need more assistance, please open a new issue that references this one.
If you wish to keep having a conversation with other community members under this issue feel free to do so.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug An issue which has been identified as a bug studio-ui An issue that needs to be tracked by Studio Console team ui-forms issues related to UI builder forms
Projects
None yet
Development

No branches or pull requests

4 participants