Jump to content

Create repeaters on module install


benbyf
 Share

Recommended Posts

Just for other peoples reference I've been using @adrian's coding here:

 as a function in my module:

protected function createRepeater($repeaterName,$repeaterFields,$repeaterLabel,$repeaterTags, $icon){
		$f = new Field();
		$f->type = $this->modules->get("FieldtypeRepeater");
		$f->name = $repeaterName;
		$f->label = $repeaterLabel;
		$f->tags = $repeaterTags;
		$f->icon = $icon;
		$f->repeaterReadyItems = 3;

		//Create fieldgroup
		$repeaterFg = new Fieldgroup();
		$repeaterFg->name = "repeater_$repeaterName";

		//Add fields to fieldgroup
		foreach($repeaterFields as $field) {
			$repeaterFg->append($this->fields->get($field));
		}

		$repeaterFg->save();

		//Create template
		$repeaterT = new Template();
		$repeaterT->name = "repeater_$repeaterName";
		$repeaterT->flags = 8;
		$repeaterT->noChildren = 1;
		$repeaterT->noParents = 1;
		$repeaterT->noGlobal = 1;
		$repeaterT->slashUrls = 1;
		$repeaterT->fieldgroup = $repeaterFg;

		$repeaterT->save();

		//Setup page for the repeater - Very important
		$repeaterPage = "for-field-{$f->id}";
		$f->parent_id = $this->pages->get("name=$repeaterPage")->id;
		$f->template_id = $repeaterT->id;
		$f->repeaterReadyItems = 3;

		//Now, add the fields directly to the repeater field
		foreach($fieldsArray as $field) {
			$f->repeaterFields = $this->fields->get($field);
		}
		$f->save();
		return $f;
	}
// usage
public function install(){
	$fields = array('title','body');
	$this->createRepeater("text_repeater",$fields,"Text repeater","", "file-text");
}

 

  • Like 5
Link to comment
Share on other sites

  • 2 years later...

For me, it looks like, adding to property repeaterFields does not work correctly. Changed it to the following:

$repeaterFieldIds = [];

foreach($fieldsArray as $field) {
  $repeaterFieldIds[] = $this->fields->get($field)->id;
}

$f->repeaterFields = $repeaterFieldIds;
    
$f->save();

 

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

×
×
  • Create New...