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

You cannot set field before registering it when set the value to dynamic form item #8880

Closed
kerrzhao opened this issue Jan 9, 2018 · 49 comments
Labels

Comments

@kerrzhao
Copy link

kerrzhao commented Jan 9, 2018

Version

3.1.1

Environment

MAC 、chrome 63.0.3239.84 (64)、antd 3.1.1

Reproduction link

https://ant.design/components/form-cn/#components-form-demo-dynamic-form-item

Steps to reproduce

Dynamic form item set value,
` const formItems = keys.map((k, index) => {
return (
<FormItem
{...formItemLayoutWithOutLabel}
required={true}
key={k}
>
{getFieldDecorator( minAmount-${k} , {
rules: [{
required: true,
message: "请输入大于0的值",
}],
})(
<InputNumber min={0.01} style={{ width: '10%', marginRight: 8 }} disabled={this.state.saveDisable} placeholder="大于0的值" step={0.01} />
)}

      { (keys.length > 1) ? (
        <Button
        type="danger"
        disabled={keys.length === 1}
        onClick={() => this.remove(k)}
        >删除</Button>
      ) : null}
    </FormItem>
  );
});

Example this.props.form.setFields( { "minAmount-1" : {value : 111} } ); .

What is expected?

Set value as common fields.

What is actually happening?

You cannot set field before registering it.


When edit the row data and set the data to dynamic form item .

@ant-design-bot
Copy link
Contributor

Hello @kerrzhao. Please provide a online reproduction by forking this link https://u.ant.design/codesandbox-repro. Issues labeled by Need Reproduce will be closed if no activities in 7 days.

@yesmeck yesmeck added the 🤔 Need Reproduce We cannot reproduce your problem label Jan 9, 2018
@kerrzhao
Copy link
Author

@yesmeck https://codesandbox.io/s/3rxj27q281 这里是代码演示。 预想效果是往动态框里设置默认值。

@yesmeck
Copy link
Member

yesmeck commented Jan 10, 2018

就像警告说的,你不能在 field 注册前去设置它的值,你在 componentDidMount 里设置 names_2 的值的时候,它还没有被注册。

@ant-design-bot
Copy link
Contributor

Hello @kerrzhao, we use GitHub issues to trace bugs or discuss plans of Ant Design. So, please don't ask usage questions here. You can try to ask questions on Stack Overflow or Segment Fault, then apply tag antd and react to your question.

@yesmeck yesmeck added the Usage label Jan 10, 2018
@yesmeck yesmeck removed the 🤔 Need Reproduce We cannot reproduce your problem label Jan 10, 2018
@gitdust
Copy link

gitdust commented Feb 7, 2018

setFieldsValue这个方法调用的时候,form没有注册,使用setFields试试看 @kerrzhao

@naefl
Copy link

naefl commented Feb 13, 2018

Same problem. English please.

@yesmeck
Copy link
Member

yesmeck commented Feb 13, 2018

@naefl As warning stated, you can not call setFieldsValue before field been registered.

@gitdust
Copy link

gitdust commented Feb 14, 2018

@naefl try 'setFields' instead

@kerrzhao
Copy link
Author

@naefl We can use the initialValue instead and set the field value to state example :https://codesandbox.io/s/3rxj27q281

@ShMcK
Copy link

ShMcK commented Feb 27, 2018

Having this same issue:

Occurs occasionally, but never the first time a component is mounted on React Native.

What is strange about this, is that setFieldValues should only be called well after the form has rendered.

class Login extends React.Component {
  componentDidMount() {
    this.getStoredSettings()
  }
  getStoredSettings = async () => {
    const canLogin = await getItem('token')
    if (!canLogin) {
      const creds = await getItem('credentials')
      if (creds) {
        // update values with creds
        const { email, password } = JSON.parse(creds)
        try {
          this.props.form.setFieldsValue({
            email,
            password,
          })
        } catch (error) {
          console.log(error)
        }
      }
    }
  }

  render() {
    const { form, initialValues } = this.props
    const { email, password } = initialValues
    const { getFieldProps } = form
    return (
            <Form>
              <InputItem
                {...getFieldProps('email', {
               initialValue: email,
             })}
              />

              <InputItem
                {...getFieldProps('password', {
               initialValue: password,
             })}
                type='password'
              />
            </Form>          
    )
  }
}

const LoginForm = createForm()(Login)

const mapState = (state) => {
  return {
    initialValues: {
      email: __DEV__ ? DEFAULT_EMAIL : '',
      password: __DEV__ ? DEFAULT_PASSWORD : '',
    },
 }
}

export default connect(mapState)(LoginForm)

@fongfai
Copy link

fongfai commented Mar 15, 2018

@gitdust dose it work ?

@gitdust
Copy link

gitdust commented Mar 15, 2018

@fenghuizhang it's work for me

@lazychanger
Copy link

why not like this ?
const formData = { name: data.name, title: data.title, desc: data.desc, link: data.link, }; this.props.form.setFieldsValue(formData);
maybe is your fields has one not in the from

@yanzishang
Copy link

if your form doesn't have the fields these you set, this error will appear!

@codesee
Copy link

codesee commented Jun 7, 2018

I having this same issue:
You cannot set field before registering it.
but the reason was finally found:I set a value to fields that form does not exist,caused an error to appear!
Thanks @yanzishang,your answer gave me great help in solving problems.

@America-first-melon
Copy link

多数是写错label了

@lehug
Copy link
Contributor

lehug commented Jul 5, 2018

if field not set, warning too.
so, first set field, like: form.getFieldDecorator('fieldName', { initialValue: {} }) in render(),
then setFieldValue in your methods.

it works for me~

@jeremymarc
Copy link

jeremymarc commented Jul 26, 2018

I'm having the same issue.

I think it's related to the field value being an object like @kerrzhao said:

Example this.props.form.setFields( { "minAmount-1" : {value : 111} } ); .

The field is set. if I do fields.hasOwnProperty(myField) it's returning true.

@guixuefeng101
Copy link

i has the same issue,the reason is that,et a value to fields that form does not exist

@GoDiMeN
Copy link

GoDiMeN commented Aug 28, 2018

@guixuefeng101 the same with me

@joeheyming
Copy link

The error should really say:
"You cannot set field before rendering a field associated with the value."

"Registering" sounds like the problem is internal to the Ant framework, and has no meaning to new developers.

@afc163
Copy link
Member

afc163 commented Aug 29, 2018

@joeheyming You can send a PR to improve that instruction.

@joeheyming
Copy link

@afc163 any pointers to where this message is? I can't find it

@joeheyming
Copy link

@chinaxiaoyy
Copy link

use getFieldDecorator's initialValue instead setFields or setFieldsValue

@wybaby168
Copy link

wybaby168 commented Oct 18, 2018

I have the similar issue, but thanks to @gitdust, your solution solved my problem perfectly.
I need to set the initial value dynamic, because there are many conditions with different initial value.
I abandoned the default initial value prop, use form.setFields before render method instead. Thanks!

@zhanghuixi
Copy link

zhanghuixi commented Jan 9, 2019

you can first set the form, like this

{ _.isEmpty(gatherDetail) && this.props.location.state.type === 'edit' ? : null }

@peakandyuri
Copy link

表单组件里只有A和B,而你set的对象里多了一个C

@hxy91819
Copy link

if your form doesn't have the fields these you set, this error will appear!

works for me , great!

@QiangJony
Copy link

How to ignore this warning?

@jackywq
Copy link

jackywq commented Jan 30, 2019

@kerrzhao I'm trying to put setFieldsValue in setState after, the warning is disappear and the problem is solved;

the code is below:

this.setState({ addOptionsList: newAddOptionsList }, () => { setFieldsValue({ [modifyedContent${value}]: '' }); });

@ecoSakuraSou
Copy link

if your form doesn't have the fields these you set, this error will appear!

sixsixsix

@ashsepra
Copy link

try form.getFieldDecorator('fieldName', { initialValue: your_value })

@wanyukang
Copy link

you should definition your fields with v-decorator in form, like:

<a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="description" hasFeedback>
    <a-textarea v-decorator="['description']"/>
</a-form-item>

document can be more clearer in this kind of important message.

@AdaXH
Copy link

AdaXH commented Mar 5, 2019

if your form doesn't have the fields these you set, this error will appear!

awesome

@zhiwenjunjin
Copy link

i had the same problem as my field name is set to a random value 'astermihagauvlent', i fixed it by changing the field name to 'keys'

@nguyenhuutinh
Copy link

initialValue is not going to change after first render, just like defaultValue. Try setFieldValue or mapPropsToFields in this situation.

example:
if(this.props.form.getFieldValue('version')){
this.props.form.setFieldsValue({
version: info.version,
});
}

@Ccheng2729111
Copy link

you set a fields which you don't have. : )

@fernandoxu
Copy link

多数是写错label了

真相了

@Xuyuey
Copy link

Xuyuey commented May 15, 2019

@ShMcK it works for me, thanks a lot :)

@jiamianmao
Copy link

getFieldsValue 即可。

@oychao
Copy link

oychao commented Jul 28, 2019

Make sure field registered before setFieldsValue

const { form } = this.props;
if (undefined !== form.getFieldValue('foo')) {
  form.setFieldsValue({
    foo: 'hello world',
  });
}

@hellohejinyu
Copy link
Contributor

if your form doesn't have the fields these you set, this error will appear!

Thx

@RusseII
Copy link

RusseII commented Nov 10, 2019

For me, the issue was due to me calling setFieldsValue with an object that had several fields, while my form only had one field.

Here is a function you can use to

const  dataIWantToFillFormWith = { "test1": "dummy data", "test2": "more dummy data" }

Object.keys(form.getFieldsValue()).forEach(key => {
      const obj = {};
      obj[key] = dataIWantToFillFormWith[key] || null;
       setFieldsValue(obj)

Using that function, it will ignore any fields that do not exist in the form.

@jackywq
Copy link

jackywq commented Nov 13, 2019

use getFieldDecorator's initialValue instead setFields or setFieldsValue

you can't use resetFields reset it when use getFieldDecorator's initialValue

@engmsilva
Copy link

For me, the issue was due to me calling setFieldsValue with an object that had several fields, while my form only had one field.

Here is a function you can use to

const  dataIWantToFillFormWith = { "test1": "dummy data", "test2": "more dummy data" }

Object.keys(form.getFieldsValue()).forEach(key => {
      const obj = {};
      obj[key] = dataIWantToFillFormWith[key] || null;
       setFieldsValue(obj)

Using that function, it will ignore any fields that do not exist in the form.

This was the only solution found in the universe that worked useEffect hooks

@bazingame
Copy link

if your form doesn't have the fields these you set, this error will appear!

love you

@leftstick
Copy link

for me, i have multiple forms. The error i found is just caused by wrong form instance, that's why i pretty sure that the field has been registered, but cannot be set value via setFieldsValue. So sad for me|_|

@1169938246
Copy link

对我来说,问题是由于我使用了具有多个字段的对象调用setFieldsValue,而我的表单只有一个字段。
这是一个你可以使用的函数

const  dataIWantToFillFormWith = { "test1": "dummy data", "test2": "more dummy data" }

Object.keys(form.getFieldsValue()).forEach(key => {
      const obj = {};
      obj[key] = dataIWantToFillFormWith[key] || null;
       setFieldsValue(obj)

使用该函数,注意表单中不存在的任何字段。

这是宇宙中发现的唯一可以使用useEffect hooks的解决方案

厉害呀,这个方法解决了我的问题,在useEffect hooks 中我想在分步表单中来收集值的问题

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests