我通过getRequest()从表单中获取了一些值 - 值很好,但只是想弄清楚如何将其保存到数据库中 - 模型已设置并且具有与表单正在发布 - 我试过这个,但它没有工作,所以很明显我必须首先转换请求数组??:
{{1}}
答案 0 :(得分:1)
$request->requestVars()
会返回一个数组......你在$ vars(一个数组)中返回的内容中使用了saveInto()方法,这是不正确的......
你应该有$form->saveInto($submission)
;
因此,这是一个非常简短的例子,说明如何使用简单的新闻稿表单和提交数据对象。
这里有一个页面控制器,其中定义了表单。当用户点击表单的提交按钮(在本例中为订阅)时,表单数据将在doSubmitNewsletterForm()
方法中处理,您基本上将提交的数据保存到新的Submission
数据对象中。
class Page_Controller extends ContentController {
private static $allowed_actions = array (
'NewsletterForm'
);
public function NewsletterForm() {
// Form Fields
$fields = FieldList::create(
$firstname = TextField::create('Firsname', 'First Name'),
$lastname = TextField::create('Lastname', 'Last Name'),
$email = EmailField::create('Email', 'Email Address')
);
// Actions
$submit = FormAction::create('doSubmitNewsletterForm', 'Subscribe');
$actions = FieldList::create($submit);
// Validators
$validator = RequiredFields::create(array('Firstname', 'Lastname', 'Email'));
// Form
$form = Form::create($this, 'NewsletterForm', $fields, $actions);
return $form;
}
/**
* Process the form data
*/
public function doSubmitNewsletterForm($data, Form $form) {
$submission = new Submission();
$form->saveInto($submission);
$submission->write();
}
}
这是提交数据对象:
class Submission extends DataObject {
private static $db = array(
'Firstname' => 'Varchar(100)',
'Lastname' => 'Varchar(100)',
'Email' => 'Varchar(100)',
);
public static getCMSFields() {
// bla bla bla
}
// bla bla bla - other methods
}
就是这样!!!
现在,如果你没有使用表格,你所能做的就是这样:
$request = $this->getRequest();
$vars = $request->requestVars();
$sumbission = new Submission();
$submission->Firstname = $vars['Firstname'];
$submission->Lastname = $vars['Lastname'];
$submission->Email = $vars['Email'];
$submission->write();
...或者你可以尝试这个(从未使用它,所以我不确定它是否会起作用):
$request = $this->getRequest();
$vars = $request->requestVars();
$submission = new Submission();
$submission->update($vars);
$submission->write();
...如果尚未保存提交数据对象,则不确定update()方法是否有效,因此如果上述方法无效,请尝试以下操作:
$submission = new Submission();
$submission->write();
$submission->update($vars);
$submission->write();
总而言之,看看DataObject类中的update()
方法(DataObject.php文件),你会看到它的作用(你会看到它所期望的唯一参数是一个数组键/值对,所以我想它应该像我上面提到的那样工作:
/**
* Update a number of fields on this object, given a map of the desired changes.
*
* The field names can be simple names, or you can use a dot syntax to access $has_one relations.
* For example, array("Author.FirstName" => "Jim") will set $this->Author()->FirstName to "Jim".
*
* update() doesn't write the main object, but if you use the dot syntax, it will write()
* the related objects that it alters.
*
* @param array $data A map of field name to data values to update.
* @return DataObject $this
*/
public function update($data) {
foreach($data as $k => $v) {
// some other core Silverstrip code
}
}