本文整理汇总了PHP中FormResponse::respond方法的典型用法代码示例。如果您正苦于以下问题:PHP FormResponse::respond方法的具体用法?PHP FormResponse::respond怎么用?PHP FormResponse::respond使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类FormResponse
的用法示例。
在下文中一共展示了FormResponse::respond方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: run
function run(DataObjectSet $pages)
{
$pageIDs = $pages->column('ID');
foreach ($pageIDs as $pageID) {
FormResponse::add("\$('Form_EditForm').reloadIfSetTo({$pageID});");
}
$this->batchaction($pages, 'batchApprove', _t('BatchApprovePages.APPROVED_PAGES', 'Approved %d pages, %d failures'));
return FormResponse::respond();
}
示例2: run
function run(DataObjectSet $pages)
{
$pageIDs = $pages->column('ID');
foreach ($pageIDs as $pageID) {
FormResponse::add("\$('Form_EditForm').reloadIfSetTo({$pageID});");
}
$count = array();
$count['PUBLISH_SUCCESS'] = $count['DELETE_SUCCESS'] = 0;
$count['PUBLISH_FAILURE'] = $count['DELETE_FAILURE'] = 0;
$arbitraryPage = $pages->First();
$arbitraryPage->invokeWithExtensions('onBeforeBatchPublish', $pages);
foreach ($pages as $page) {
$type = $page->openWorkflowRequest() instanceof WorkflowDeletionRequest ? 'DELETE' : 'PUBLISH';
if ($page->batchPublish()) {
$count[$type . '_SUCCESS']++;
// Now make sure the tree title is appropriately updated
$publishedRecord = DataObject::get_by_id('SiteTree', $page->ID);
if ($publishedRecord) {
$JS_title = Convert::raw2js($publishedRecord->TreeTitle());
FormResponse::add("\$('sitetree').setNodeTitle({$page->ID}, '{$JS_title}');");
}
} else {
$count[$type . '_FAILURE']++;
FormResponse::add("\$('sitetree').addNodeClassByIdx('{$page->ID}', 'failed');");
}
$page->destroy();
unset($page);
}
$arbitraryPage->invokeWithExtensions('onAfterBatchPublish', $pages);
$messages = array('PUBLISH_SUCCESS' => _t('BatchPublishPages.PUBLISH_SUCCESS', 'Published %d pages.'), 'PUBLISH_FAILURE' => _t('BatchPublishPages.PUBLISH_FAILURE', 'Failed to publish %d pages.'), 'DELETE_SUCCESS' => _t('BatchPublishPages.DELETE_SUCCESS', 'Deleted %d pages from the published site.'), 'DELETE_FAILURE' => _t('BatchPublishPages.DELETE_FAILURE', 'Failed to delete %d pages from the published site.'), 'PUBLISH_SUCCESS_ONE' => _t('BatchPublishPages.PUBLISH_SUCCESS_ONE', 'Published %d page.'), 'PUBLISH_FAILURE_ONE' => _t('BatchPublishPages.PUBLISH_FAILURE_ONE', 'Failed to publish %d page.'), 'DELETE_SUCCESS_ONE' => _t('BatchPublishPages.DELETE_SUCCESS_ONE', 'Deleted %d page from the published site.'), 'DELETE_FAILURE_ONE' => _t('BatchPublishPages.DELETE_FAILURE_ONE', 'Failed to delete %d page from the published site.'));
$displayedMessages = array();
foreach ($count as $type => $count) {
if ($count) {
$message = $count == 1 ? $messages[$type . '_ONE'] : $messages[$type];
$displayedMessages[] = sprintf($message, $count);
}
}
$displayedMessage = implode(" ", $displayedMessages);
FormResponse::add('statusMessage("' . $displayedMessage . '","good");');
return FormResponse::respond();
}
示例3: moderate
function moderate()
{
$id = (int) $this->urlParams['ID'];
$className = Convert::raw2sql($this->urlParams['ClassName']);
$state = Convert::raw2sql($this->urlParams['State']);
$methods = array("delete" => "moderatorDelete", "isspam" => "markSpam", "isham" => "markHam", "approve" => "markApproved", "unapprove" => "markUnapproved");
ModeratableState::push_state($state);
$method = $methods[$this->urlParams['Command']];
if (!$method) {
FormResponse::clear();
FormResponse::status_message("Command invalid", 'bad');
} else {
if ($error = DataObject::get_by_id($className, $id)->{$method}()) {
FormResponse::status_message($error, 'bad');
} else {
FormResponse::add('$("moderation").elementMoved(' . $id . ');');
}
}
ModeratableState::pop_state();
return FormResponse::respond();
}
示例4: doPublish
/**
* When an error page is published, create a static HTML page with its
* content, so the page can be shown even when SilverStripe is not
* functioning correctly before publishing this page normally.
* @param string|int $fromStage Place to copy from. Can be either a stage name or a version number.
* @param string $toStage Place to copy to. Must be a stage name.
* @param boolean $createNewVersion Set this to true to create a new version number. By default, the existing version number will be copied over.
*/
function doPublish()
{
parent::doPublish();
// Run the page
$response = Director::test(Director::makeRelative($this->Link()));
$errorContent = $response->getBody();
// Check we have an assets base directory, creating if it we don't
if (!file_exists(ASSETS_PATH)) {
mkdir(ASSETS_PATH, 02775);
}
// if the page is published in a language other than default language,
// write a specific language version of the HTML page
$filePath = self::get_filepath_for_errorcode($this->ErrorCode, $this->Locale);
if ($fh = fopen($filePath, "w")) {
fwrite($fh, $errorContent);
fclose($fh);
} else {
$fileErrorText = sprintf(_t("ErrorPage.ERRORFILEPROBLEM", "Error opening file \"%s\" for writing. Please check file permissions."), $errorFile);
FormResponse::status_message($fileErrorText, 'bad');
FormResponse::respond();
return;
}
}
示例5: startrun
public function startrun()
{
$task = new LinkCheckTask();
$result = $task->process();
$script = '';
if (class_exists('SapphireTest', false) && SapphireTest::is_running_test()) {
return;
}
if (!$result) {
FormResponse::status_message('There is already a link check running at the moment. Please wait for it to complete before starting a new one.', 'bad');
return FormResponse::respond();
}
if (!empty($result['LinkCheckRunID'])) {
$run = DataObject::get_by_id('LinkCheckRun', (int) $result['LinkCheckRunID']);
if ($run) {
echo $this->addTreeNodeJS($run, true);
}
}
}
示例6: doPublish
/**
* When an error page is published, create a static HTML page with its
* content, so the page can be shown even when SilverStripe is not
* functioning correctly before publishing this page normally.
* @param string|int $fromStage Place to copy from. Can be either a stage name or a version number.
* @param string $toStage Place to copy to. Must be a stage name.
* @param boolean $createNewVersion Set this to true to create a new version number. By default, the existing version number will be copied over.
*/
function doPublish()
{
parent::doPublish();
// Run the page (reset the theme, it might've been disabled by LeftAndMain::init())
$oldTheme = SSViewer::current_theme();
SSViewer::set_theme(SSViewer::current_custom_theme());
$response = Director::test(Director::makeRelative($this->Link()));
SSViewer::set_theme($oldTheme);
$errorContent = $response->getBody();
// Make the base tag dynamic.
// $errorContent = preg_replace('/<base[^>]+href="' . str_replace('/','\\/', Director::absoluteBaseURL()) . '"[^>]*>/i', '<base href="$BaseURL" />', $errorContent);
// Check we have an assets base directory, creating if it we don't
if (!file_exists(ASSETS_PATH)) {
mkdir(ASSETS_PATH, 02775);
}
// if the page is published in a language other than default language,
// write a specific language version of the HTML page
$filePath = self::get_filepath_for_errorcode($this->ErrorCode, $this->Locale);
if ($fh = fopen($filePath, "w")) {
fwrite($fh, $errorContent);
fclose($fh);
} else {
$fileErrorText = sprintf(_t("ErrorPage.ERRORFILEPROBLEM", "Error opening file \"%s\" for writing. Please check file permissions."), $errorFile);
FormResponse::status_message($fileErrorText, 'bad');
FormResponse::respond();
return;
}
}
示例7: exportastarball
public function exportastarball()
{
$template = $this->getCurrentDynamicTemplate();
if (!$template) {
FormResponse::status_message("No template selected, Please select template");
FormResponse::load_form($this->getitem(), 'Form_EditForm');
return FormResponse::respond();
} else {
$fileData = $template->exportAs("tar.gz");
$fileName = $template->Name . ".tar.gz";
return SS_HTTPRequest::send_file($fileData, $fileName, "application/x-tar");
}
}
示例8: createtranslation
/**
* Create a new translation from an existing item, switch to this language and reload the tree.
*/
function createtranslation($request)
{
// Protect against CSRF on destructive action
if (!SecurityToken::inst()->checkRequest($request)) {
return $this->httpError(400);
}
$langCode = Convert::raw2sql($_REQUEST['newlang']);
$originalLangID = (int) $_REQUEST['ID'];
$record = $this->getRecord($originalLangID);
$this->Locale = $langCode;
Translatable::set_current_locale($langCode);
// Create a new record in the database - this is different
// to the usual "create page" pattern of storing the record
// in-memory until a "save" is performed by the user, mainly
// to simplify things a bit.
// @todo Allow in-memory creation of translations that don't persist in the database before the user requests it
$translatedRecord = $record->createTranslation($langCode);
$url = sprintf("%s/%d/?locale=%s", $this->Link('show'), $translatedRecord->ID, $langCode);
FormResponse::add(sprintf('window.location.href = "%s";', $url));
return FormResponse::respond();
}
示例9: publish
/**
* When an error page is published, create a static HTML page with its
* content, so the page can be shown even when SilverStripe is not
* functioning correctly before publishing this page normally.
* @param string|int $fromStage Place to copy from. Can be either a stage name or a version number.
* @param string $toStage Place to copy to. Must be a stage name.
* @param boolean $createNewVersion Set this to true to create a new version number. By default, the existing version number will be copied over.
*/
function publish($fromStage, $toStage, $createNewVersion = false) {
$oldStage = Versioned::current_stage();
// Run the page
$response = Director::test(Director::makeRelative($this->Link()));
$errorContent = $response->getBody();
// Check we have an assets base directory, creating if it we don't
if(!file_exists(ASSETS_PATH)) {
mkdir(ASSETS_PATH, 02775);
}
// Path to the error file in the file store
$errorFile = ASSETS_PATH . "/error-$this->ErrorCode.html";
// Attempt to open the file, writing it if it doesn't exist
$fh = @fopen($errorFile, "w");
if($fh) {
fwrite($fh, $errorContent);
fclose($fh);
} else {
$fileErrorText = sprintf(
_t(
"ErrorPage.ERRORFILEPROBLEM",
"Error opening file \"%s\" for writing. Please check file permissions."
),
$errorFile
);
FormResponse::status_message($fileErrorText, 'bad');
FormResponse::respond();
return;
}
// Restore the version we're currently connected to.
Versioned::reading_stage($oldStage);
return $this->extension_instances['Versioned']->publish($fromStage, $toStage, $createNewVersion);
}
示例10: httpSubmission
/**
* Handle a form submission. GET and POST requests behave identically.
* Populates the form with {@link loadDataFrom()}, calls {@link validate()},
* and only triggers the requested form action/method
* if the form is valid.
*/
function httpSubmission($request) {
$vars = $request->requestVars();
if(isset($funcName)) {
Form::set_current_action($funcName);
}
// Populate the form
$this->loadDataFrom($vars, true);
// Validate the form
if(!$this->validate()) {
if(Director::is_ajax()) {
return FormResponse::respond();
} else {
Director::redirectBack();
return;
}
}
// Protection against CSRF attacks
if($this->securityTokenEnabled()) {
$securityID = Session::get('SecurityID');
if(!$securityID || !isset($vars['SecurityID']) || $securityID != $vars['SecurityID']) {
$this->httpError(400, "SecurityID doesn't match, possible CRSF attack.");
}
}
// Determine the action button clicked
$funcName = null;
foreach($vars as $paramName => $paramVal) {
if(substr($paramName,0,7) == 'action_') {
// Break off querystring arguments included in the action
if(strpos($paramName,'?') !== false) {
list($paramName, $paramVars) = explode('?', $paramName, 2);
$newRequestParams = array();
parse_str($paramVars, $newRequestParams);
$vars = array_merge((array)$vars, (array)$newRequestParams);
}
// Cleanup action_, _x and _y from image fields
$funcName = preg_replace(array('/^action_/','/_x$|_y$/'),'',$paramName);
break;
}
}
// If the action wasnt' set, choose the default on the form.
if(!isset($funcName) && $defaultAction = $this->defaultAction()){
$funcName = $defaultAction->actionName();
}
if(isset($funcName)) {
$this->setButtonClicked($funcName);
}
// First, try a handler method on the controller
if($this->controller->hasMethod($funcName)) {
return $this->controller->$funcName($vars, $this, $request);
// Otherwise, try a handler method on the form object
} else {
return $this->$funcName($vars, $this, $request);
}
}
示例11: beforeProcessing
/**
* Processing that occurs before a form is executed.
* This includes form validation, if it fails, we redirect back
* to the form with appropriate error messages
*/
function beforeProcessing()
{
if ($this->validator) {
$errors = $this->validator->validate();
if ($errors) {
if (Director::is_ajax()) {
// Send validation errors back as JSON with a flag at the start
//echo "VALIDATIONERROR:" . Convert::array2json($errors);
FormResponse::status_message(_t('Form.VALIDATIONFAILED', 'Validation failed'), 'bad');
foreach ($errors as $error) {
FormResponse::add(sprintf("validationError('%s', '%s', '%s');\n", Convert::raw2js($error['fieldName']), Convert::raw2js($error['message']), Convert::raw2js($error['messageType'])));
}
echo FormResponse::respond();
return false;
} else {
$data = $this->getData();
// People will get worried if you leave credit card information in session..
if (isset($data['CreditCardNumber'])) {
unset($data['CreditCardNumber']);
}
if (isset($data['DateExpiry'])) {
unset($data['Expiry']);
}
// Load errors into session and post back
Session::set("FormInfo.{$this->FormName()}", array('errors' => $errors, 'data' => $data));
Director::redirectBack();
}
return false;
}
}
return true;
}
示例12: httpSubmission
function httpSubmission($request)
{
$vars = $request->requestVars();
if (isset($funcName)) {
Form::set_current_action($funcName);
}
// Populate the form
$this->loadDataFrom($vars, true);
// Protection against CSRF attacks
$token = $this->getSecurityToken();
if (!$token->checkRequest($request)) {
$this->httpError(400, _t('AdvancedWorkflowFrontendForm.SECURITYTOKENCHECK', "Security token doesn't match, possible CSRF attack."));
}
// Determine the action button clicked
$funcName = null;
foreach ($vars as $paramName => $paramVal) {
if (substr($paramName, 0, 7) == 'action_') {
// Added for frontend workflow form - get / set transitionID on controller,
// unset action and replace with doFrontEndAction action
if (substr($paramName, 0, 18) == 'action_transition_') {
$this->controller->transitionID = substr($paramName, strrpos($paramName, '_') + 1);
unset($vars['action_transition_' . $this->controller->transitionID]);
$vars['action_doFrontEndAction'] = 'doFrontEndAction';
$paramName = 'action_doFrontEndAction';
$paramVal = 'doFrontEndAction';
}
// Break off querystring arguments included in the action
if (strpos($paramName, '?') !== false) {
list($paramName, $paramVars) = explode('?', $paramName, 2);
$newRequestParams = array();
parse_str($paramVars, $newRequestParams);
$vars = array_merge((array) $vars, (array) $newRequestParams);
}
// Cleanup action_, _x and _y from image fields
$funcName = preg_replace(array('/^action_/', '/_x$|_y$/'), '', $paramName);
break;
}
}
// If the action wasnt' set, choose the default on the form.
if (!isset($funcName) && ($defaultAction = $this->defaultAction())) {
$funcName = $defaultAction->actionName();
}
if (isset($funcName)) {
$this->setButtonClicked($funcName);
}
// Permission checks (first on controller, then falling back to form)
if ($this->controller->hasMethod($funcName) && !$this->controller->checkAccessAction($funcName) && !$this->Actions()->fieldByName('action_' . $funcName)) {
return $this->httpError(403, sprintf(_t('AdvancedWorkflowFrontendForm.ACTIONCONTROLLERCHECK', 'Action "%s" not allowed on controller (Class: %s)'), $funcName, get_class($this->controller)));
} elseif ($this->hasMethod($funcName) && !$this->checkAccessAction($funcName)) {
return $this->httpError(403, sprintf(_t('AdvancedWorkflowFrontendForm.ACTIONFORMCHECK', 'Action "%s" not allowed on form (Name: "%s")'), $funcName, $this->Name()));
}
if ($wfTransition = $this->controller->getCurrentTransition()) {
$wfTransType = $wfTransition->Type;
} else {
$wfTransType = null;
//ie. when a custom Form Action is defined in WorkflowAction
}
// Validate the form
if (!$this->validate() && $wfTransType == 'Active') {
if (Director::is_ajax()) {
// Special case for legacy Validator.js implementation (assumes eval'ed javascript collected through FormResponse)
if ($this->validator->getJavascriptValidationHandler() == 'prototype') {
return FormResponse::respond();
} else {
$acceptType = $request->getHeader('Accept');
if (strpos($acceptType, 'application/json') !== FALSE) {
// Send validation errors back as JSON with a flag at the start
$response = new SS_HTTPResponse(Convert::array2json($this->validator->getErrors()));
$response->addHeader('Content-Type', 'application/json');
} else {
$this->setupFormErrors();
// Send the newly rendered form tag as HTML
$response = new SS_HTTPResponse($this->forTemplate());
$response->addHeader('Content-Type', 'text/html');
}
return $response;
}
} else {
if ($this->getRedirectToFormOnValidationError()) {
if ($pageURL = $request->getHeader('Referer')) {
if (Director::is_site_url($pageURL)) {
// Remove existing pragmas
$pageURL = preg_replace('/(#.*)/', '', $pageURL);
return Director::redirect($pageURL . '#' . $this->FormName());
}
}
}
return Director::redirectBack();
}
}
// First, try a handler method on the controller (has been checked for allowed_actions above already)
if ($this->controller->hasMethod($funcName)) {
return $this->controller->{$funcName}($vars, $this, $request);
// Otherwise, try a handler method on the form object.
} elseif ($this->hasMethod($funcName)) {
return $this->{$funcName}($vars, $this, $request);
}
return $this->httpError(404);
}
示例13: deleteunusedthumbnails
/**
* Removes all unused thumbnails from the file store
* and returns the status of the process to the user.
*/
public function deleteunusedthumbnails()
{
$count = 0;
$thumbnails = $this->getUnusedThumbnails();
if ($thumbnails) {
foreach ($thumbnails as $thumbnail) {
unlink(ASSETS_PATH . "/" . $thumbnail);
$count++;
}
}
$message = sprintf(_t('AssetAdmin.THUMBSDELETED', '%s unused thumbnails have been deleted'), $count);
FormResponse::status_message($message, 'good');
echo FormResponse::respond();
}
示例14: javascriptRefresh
protected function javascriptRefresh($message = 'Please wait...')
{
FormResponse::add("\$('Form_EditForm').resetElements();");
FormResponse::add('$$("#sitetree li.current")[0].selectTreeNode();');
FormResponse::status_message($message, "good");
return FormResponse::respond();
}
示例15: getRelatedData
protected function getRelatedData()
{
$relatedName = $_REQUEST['RelatedClass'];
$id = $_REQUEST[$relatedName]['ID'];
$baseClass = $this->stat('data_type');
$relatedClasses = singleton($baseClass)->stat('has_one');
if ($id) {
$relatedObject = DataObject::get_by_id($relatedClasses[$relatedName], $id);
$response .= <<<JS
\t\t\t\$('{$relatedName}').unsetNewRelatedKey();
JS;
} elseif ($id !== '0') {
//in case of null;
$relatedObject = new $relatedClasses[$relatedName]();
if ($parentID = $_REQUEST[$relatedName]['ParentID']) {
$relatedObject->ParentID = $parentID;
}
$id = $relatedObject->write();
$response .= <<<JS
\t\t\t\$('{$relatedName}').setNewRelatedKey({$id});
JS;
} else {
// in case of 0
$relatedObject = new $relatedClasses[$relatedName]();
if ($parentID = $_REQUEST[$relatedName]['ParentID']) {
$relatedObject->ParentID = $parentID;
}
$response .= <<<JS
\t\t\t\$('{$relatedName}').unsetNewRelatedKey();
JS;
}
if (Director::is_ajax()) {
$fields = $_REQUEST[$relatedName];
$response .= <<<JS
var dataArray = new Array();
JS;
foreach ($fields as $k => $v) {
$JS_newKey = Convert::raw2js($relatedName . '[' . $k . ']');
$JS_newValue = Convert::raw2js($relatedObject->{$k});
$response .= <<<JS
dataArray['{$JS_newKey}'] = '{$JS_newValue}';
JS;
}
$response .= <<<JS
\$('{$relatedName}').updateChildren(dataArray, true);
JS;
FormResponse::add($response);
}
return FormResponse::respond();
}