why did I get this bad request (#400) error after submitting my update on my ‘news’ section :
Missing required parameters: id
This is my update function
php
public function actionUpdate($id)
{
$model = $this->findModel($id);
$oldFile = $model->getImageFile();
$currentImage=$model->image;
if ($model->load(Yii::$app->request->post())) {
// process uploaded image file instance
$image = $model->uploadImage();
// revert back if no valid file instance uploaded
if ($image === false) {
$model->image = $currentImage;
}
if ($model->save()) {
// upload only if valid uploaded file instance found
if ($image !== false && unlink($oldFile)) { // delete old and overwrite
$path = $model->getImageFile();
$image->saveAs($path);
}
return $this->redirect(['view', ['id'=>$model->id,'image'=>$model->image],
]);
}
} else {
return $this->render('update', [
'model'=>$model,
]);
}
}
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
Please note that the updating and uploading image process were actually a success (that’s why I didn’t show my model’s method code that my actionUpdate called). If I go directly to view the recently updated page and view the content, it clearly displays the updated contents along with the image without problem. The error only occurs just right after the update is submitted. I thought I had pass the parameter after the update by this line :
return $this->redirect(['view', ['id'=>$model->id,'image'=>$model->image],
Right before that line I even echo $model->id to test and it echoed out the id.
I’ve looked for similar problem in StackOverflow and find someone suggested this :
php
if($model->save())
{
$lastInsertID = $model->getPrimaryKey();
return $this->redirect(['view', 'id' => $lastInsertID]);
}
But it didn’t work. Any idea?
Здравствуйте, я понимаю что ошибка возникла из-за путаницы переменных, хотя это мои предположения.. Дело в том, что данная ошибка возникла в обновлении и в просмотре: update и view. Я уже всё испробовала.. Ткните пожалуйста носом где я ошиблась?
Контроллер:
<?php
namespace app\modules\admin\controllers;
use app\modules\admin\models\FaqLang;
use Yii;
use app\modules\admin\models\Faq;
use app\modules\admin\models\FaqSearch;
use yii\base\Model;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* FaqsController implements the CRUD actions for Faq model.
*/
class FaqsController extends Controller
{
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Faq models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new FaqSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Faq model.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
return $this->render('view', [
'faq' => $this->findModel($id),
]);
}
/**
* Creates a new Faq model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$faq = new FaqLang;
$faqLang = new Faq;
if ($faq->load(Yii::$app->request->post()) && $faqLang->load(Yii::$app->request->post()) && Model::validateMultiple([$faq, $faqLang]))
{
$faqLang->save(false);
$faq->faq_id = $faq->id;
$faq->save(false);
return $this->redirect(['view', 'id' => $faq->id]);
}
return $this->render('create', [
'faqLang' => $faqLang,
'faq' => $faq,
]);
}
/**
* Updates an existing Faq model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$faq = FaqLang::findOne($id);
$faqLang = Faq::findOne($faq->faq_id);
if ($faq->load(Yii::$app->request->post()) && $faqLang->load(Yii::$app->request->post()) && Model::validateMultiple([$faq, $faqLang]))
{
$faqLang->save(false);
$faq->save(false);
return $this->redirect(['view', 'id' => $faq->id]);
}
return $this->render('update', [
'faq' => $faq,
'faqLang' => $faqLang,
]);
}
/**
* Deletes an existing Faq model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$id_ = FaqLang::findOne($id)->faq_id;
Faq::findOne($id)->delete();
Faq::findOne($id_)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Faq model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return FaqLang
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($faq = FaqLang::findOne($id)) !== null) {
return $faq;
}
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel app\modules\admin\models\FaqSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = Yii::t('app', 'Faqs');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="faq-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a(Yii::t('app', 'Create Faq'), ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
['attribute' => 'name', 'value' => 'faqLang.name'],
['attribute' => 'body', 'value' => 'faqLang.body:ntext'],
'put_date',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
view.php
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $faqLang app\modules\admin\models\Faq */
/* @var $faq app\modules\admin\models\FaqLang */
//$this->title = $faq->id;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Faqs'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="faq-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a(Yii::t('app', 'Update'), ['update', 'id' => $faq->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a(Yii::t('app', 'Delete'), ['delete', 'id' => $faq->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Are you sure you want to delete this item?'),
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'faq' => $faq,
'attributes' => [
'id',
['attribute' => 'name', 'value' => 'faqLang.name'],
['attribute' => 'body', 'value' => 'faqLang.body:ntext'],
'put_date',
[
'attribute' => 'hide',
'format' => 'html',
'value' => function($model) {
if($model->hide == 'show')
return 'Нет';
else
return 'Да';
}
],
],
]) ?>
</div>
update.php
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $faqLang app\modules\admin\models\Faq */
/* @var $faq app\modules\admin\models\FaqLang */
$this->title = Yii::t('app', 'Update Faq: ' . $faq->id, [
'nameAttribute' => '' . $faq->id,
]);
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Faqs'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $faq->id, 'url' => ['view', 'id' => $faq->id]];
$this->params['breadcrumbs'][] = Yii::t('app', 'Update');
?>
<div class="faq-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'faq' => $faq,
'faqLang' => $faqLang,
]) ?>
</div>
create.php
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $faqLang app\modules\admin\models\Faq */
/* @var $faq app\modules\admin\models\FaqLang */
$this->title = Yii::t('app', 'Create Faq');
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Faqs'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="faq-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'faq' => $faq,
'faqLang' => $faqLang,
]) ?>
</div>
form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\jui\DatePicker;
use mihaildev\ckeditor\CKEditor;
/* @var $this yii\web\View */
/* @var $faqLang app\modules\admin\models\Faq */
/* @var $faq app\modules\admin\models\FaqLang */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="faq-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($faq, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($faq, 'body')->widget(CKEditor::className(),[
'editorOptions' => [
'preset' => 'full', //разработанны стандартные настройки basic, standard, full данную возможность не обязательно использовать
'inline' => false, //по умолчанию false
],
]); ?>
<?= $form->field($faqLang, 'put_date')->widget(DatePicker::class, [
'language' => 'ru-RU',
'dateFormat' => 'yyyy-MM-dd',
]) ?>
<?= $form->field($faqLang, 'hide')->dropDownList([ 'show' => 'Отображать', 'hide' => 'Скрыто']) ?>
<div class="form-group" style="margin-top: 46px;">
<?= Html::submitButton($faqLang->isNewRecord ? 'Создать' : 'Редактировать', ['class' => $faqLang->isNewRecord ? 'btn btn-success' : 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Создаю страницу через API:
<?php
require_once(‘../../config.php’);
$cmid = required_param(‘id’, PARAM_INT);
$cm = get_coursemodule_from_id(‘mymodulename’, $cmid, 0, false, MUST_EXIST);
$course = $DB->get_record(‘course’, array(‘id’ => $cm->course), ‘*’, MUST_EXIST);
require_login($course, true, $cm);
$PAGE->set_url(‘/mod/mymodulename/view.php’, array(‘id’ => $cm->id));
$PAGE->set_title(‘My modules page title’);
$PAGE->set_heading(‘My modules page heading’);
?>
При переходе получаю такую ошибку:
Страницу создаю без использования админки, то есть ввожу код, указанный выше непосредственно в …php-файл.
Moodle 3, развивающий блок
Я получаю следующую ошибку: «Отсутствует обязательный параметр (id)».
Это происходит в $mform, только когда я использую массив (‘id’ => $instance->id) в операторе ‘Else if’ в перенаправлении ($url).
Удивительно, потому что, когда я использую тот же код в кнопке с URL-адресом перенаправления, код работает правильно.
Я пробовал несколько вещей, но ничего не помогает. В чем может быть проблема?
Вот некоторый код:
$id = required_param('id', PARAM_INT);
$instance = $DB->get_record('block_instances', array('id' => $id), '*', MUST_EXIST);
$context = \context_block::instance($instance->id);
$mform = new newlink();
if ($mform->is_cancelled()) {
$url = new moodle_url('/my');
redirect($url);
} else if ($fromform = $mform->get_data()) {
// data from form
....
$url = new moodle_url('/blocks/name_of_block/links.php', array('id' => $instance->id)); // HERE IS THE PROBLEM
(Note: when I'm using here the block instance id number 123 directly, the redirect is working correct:
$url = new moodle_url('/blocks/name_of_block/links.php?id=123';)
redirect ($url);
} else {
//Set default data (if any)
$mform->set_data($toform);
//displays the form
$mform->display();
}
$url = new moodle_url('/blocks/name_of_block/links.php', array('id' => $instance->id))
echo $OUTPUT->single_button($url, get_string('button:links', 'block_name_of_block')); // THIS IS WORKING CORRECT
2016-06-25 13:35
1
ответ
Решение
Это когда вы отправляете форму, а не редирект?
В вашей форме у вас есть:
$mform->addElement('hidden', 'id');
$mform->setType('id', PARAM_INT);
и в приведенном выше коде у вас есть:
$toform->id = $id;
$mform->set_data($toform);
2016-06-25 19:25
Добрый день.
Столкнулась с проблемой удаления записей.
Сам экшн — стандартный:
Код: Выделить всё
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
ID передается из виджета GridView. В общем все стандартно. Однако получаю ошибку:
Bad Request (#400) Отсутствуют обязательные параметры: id
При этом удаление выполняется. Т.е. если вернуться к списку записей — то там этой записи нет (в таблице БД соответственно).
Попробовала изменить ссылку в GridView, чтоб уже руками явно прописать ID:
Код: Выделить всё
...
'buttons'=>[
'delete'=>function($url,$data){
return Html::a('<span class="glyphicon glyphicon-trash"></span>',['/track/delete','id'=>$data->id],['data-method'=>'post']);
}
]
...
результат тот же.
Подскажите, в чем может быть проблема?
Спасибо.