Jump to content
muzzer

Add repeater using API - clarification

Recommended Posts

Using repeaters for the first time and wanted some clarification; In the repeater documentation it provides sample code for adding a new repeater via the api:

$building = $page->buildings->getNew();
$building->title = 'One Atlantic Center';
$building->feet_high = 880;
$building->num_floors = 50;
$building->year_built = 1997;
$building->save();
$page->buildings->add($building);    
$page->save();

Okay, I've followed this with my code as follows:

$pg = wire('pages')->get(86040);

$newroom = $pg->sRoomsRepeater->getNew();
$newroom->title = 'new room';
$newroom->sRoomType = 85952;
$newroom->sPriceBand = 85984;
$newroom->sPrice = '300.00';
$newroom->save();

and a new repeater is added to the page. Sweet. I go into the PW admin and confirm it is indeed added to the page.

Ryan states:

You may call getNew() on any repeater field to get a new item. The item that it returns is ready to populate and has already been added to the repeater

So calling getNew() followed by save() creates and saves the new repeater item. What I don't understand is the final two lines of Ryans sample where he uses the add method - what is this for? In my code the new repeater field is already added and saved into the page without using this method. What am I missing?

Share this post


Link to post
Share on other sites

The last 2 lines add the temporary repeater "item" you just created into the actual repeater field "array"

Share this post


Link to post
Share on other sites

Hi, 

I'm resurrecting this old thread, because it's spot-on for my issue :

Rather up to date PW version here (3.0.153.

With the above code, my repeater field eventually contains 3 new items (all identical), instead of 1 !

More precisely :

 

// here, $page->buildings->count() returns 0  (all right)
$building = $page->buildings->getNew();
$building->title = 'One Atlantic Center';
$building->blabla = 'test';
$building->save();
// here, $page->buildings->count() returns 1  (that's understandable)
$page->buildings->add($building);
// here, $page->buildings->count() returns 2 (ouch !)
$page->save();
// here, $page->buildings->count() returns 3 (ouch !!)
// and in the admin GUI, there's 3 new items (all identical)

 

-> Has anyone noticed this behaviour ?

As a workaround, I may skip the ->add() step (despite that this step is the API-documented way of doing things),
but even then, the $page->save() is still creating a second identical item ; and this is a problem...

 

 

 

 

Share this post


Link to post
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

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...