Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We're retiring the forums!

The SilverStripe forums have passed their heyday. They'll stick around, but will be read only. We'd encourage you to get involved in the community via the following channels instead:

Form Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Multiple DataObjects (of the same type) on the same form...


Go to End


2 Posts   984 Views

Avatar
swaiba

Forum Moderator, 1899 Posts

11 November 2010 at 7:23am

Hello, I'm trying to work out how to show on a single form multiple instances on the same form, so...

class ObjOne extends DataObject{
	static $db = array('ItemOne'=>'Text');
}
class ObjTwo extends DataObject{
	static $db = array('ItemTwo'=>'Text');
}

...

//I'd like to do the following to create the fields...
$fields = new FieldSet();
for($i=0;$i<5;$i++)
	$fields->merge(singleton('ObjOne')->getFrontendFields());
for($i=0;$i<10;$i++)
	$fields->merge(singleton('ObjTwo')->getFrontendFields());

...

//then do something like this in the form action to save them... (where $data is the data passed from the form)

for($i=0;$i<5;$i++){
	$doObjOne= new ObjOne($data);
	$doObjOne->write();
}
for($i=0;$i<10;$i++){
	$doObjTwo= new ObjOne($data);
	$doObjTwo->write();
}

Can someone help with a way of doing this without having to go "long hand" and specify everything field and then set each field at the end manually?

Barry

Avatar
swaiba

Forum Moderator, 1899 Posts

11 November 2010 at 1:25pm

Ok, solved, thanks Martijn for the idea...


	function TestForm()
	{
		$fields = new FieldSet();

		for($i=0;$i<5;$i++){
			$fieldsa = singleton('ObjOne')->getFrontendFields();

			foreach ($fieldsa as $f){
				$name = $f->Name();
				$f->setName("ObjOne_{$i}_{$name}");
				$fields->push($f);
			}
		}

		for($i=0;$i<10;$i++){
			$fieldsb = singleton('ObjTwo')->getFrontendFields();
			foreach ($fieldsb as $f){
				$name = $f->Name();

				$f->setName("ObjTwo_{$i}_{$name}");
				$fields->push($f);
			}
		}

		$actions = new FieldSet(new FormAction('DoTestForm', 'go'));

		return new Form($this, 'TestForm', $fields, $actions, new RequiredFields());
	}


	function DoTestForm($data,$form)
	{
		$fieldsa = singleton('ObjOne')->getFrontendFields();
		$fieldsb = singleton('ObjTwo')->getFrontendFields();

		for($i=0;$i<5;$i++){
			$doObjOne= new ObjOne();
			foreach ($fieldsa as $f){
				$name = $f->Name();
				$key = "ObjOne_{$i}_$name";

				$doObjOne->$name = $data[$key];
			}
			$doObjOne->write();
		}
		for($i=0;$i<10;$i++){
			$doObjTwo = new ObjTwo();
			foreach ($fieldsb as $f){
				$name = $f->Name();
				$key = "ObjTwo_{$i}_$name";

				$doObjTwo->$name = $data[$key];
			}
			$doObjTwo->write();
		}

		return Director::redirect(Director::baseURL(). $this->URLSegment.'?posted=1');
	}