Jump to content

Issues of adding Page with Repeater field by API


Karl_T
 Share

Recommended Posts

Greetings. I am trying to use API to add new page with a repeater field. I am following this link https://processwire.com/api/fieldtypes/repeaters/.

Using the code similar as below.

$p = new Page();
$p->parent = wire("pages")->get("template=something");
$p->template = 'some-template-name';
$p->name = 'some-name';
$r = $p->repeater->getNew();
$r->field1 = 'somthing';
$r->field2 = 'somthing';
$r->field3 = 'somthing';
$r->save();
$p->repeater->add($r);
$p->save();

The page is added successfully, but, with 2 identical repeater item inside the repeater field. This is the first issue.

And then I remove the second last line and become

$p = new Page();
$p->parent = wire("pages")->get("template=something");
$p->template = 'some-template-name';
$p->name = 'some-name';
$r = $p->repeater->getNew();
$r->field1 = 'somthing';
$r->field2 = 'somthing';
$r->field3 = 'somthing';
$r->save();
$p->save();

The duplicated issue is gone. The second issue then comes.

When adding new page using above code, a repeater page with same title is added under the path /cms/repeaters/for-field-280/for-page-0/, while the normal one is added under /cms/repeaters/for-field-280/for-page-2011/. The page /cms/repeaters/for-field-280/for-page-0/ cannot be deleted. And the children page under it just keeps growing when I add new page. I believe this is the cache remained because I deleted the line. I think I can just leave the page there, but I cannot. I don't want unwanted things appear and grow.

Maybe I have missed something. I want a proper way to add page with repeater fields. Thanks!

Link to comment
Share on other sites

I think you need to save the new page before adding the repeater item to it.

$p = new Page();
$p->parent = wire("pages")->get("template=something");
$p->template = 'some-template-name';
$p->name = 'some-name';
$p->save(); // save the page here
$r = $p->repeater->getNew();
$r->field1 = 'somthing';
$r->field2 = 'somthing';
$r->field3 = 'somthing';
$r->save();
$p->repeater->add($r);
$p->save(); // save again after adding the repeater item

 

  • Like 4
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...