yiisoft / yii2

Yii 2: The Fast, Secure and Professional PHP Framework
http://www.yiiframework.com
BSD 3-Clause "New" or "Revised" License
14.23k stars 6.91k forks source link

Invalid argument supplied for foreach() #7917

Closed packcode closed 9 years ago

packcode commented 9 years ago

Hello guys, i am trying to collect tabular input from users below is my code when the ajax call returns from actionAddmore(), to userform.php page i am getting an error as "Invalid arguments supplied for foreach" can anyone help me. controller:

 public function actionCreate()
    {
        $model = array();
        $model[] = new Instructions();
        if (Yii::$app->request->post() && $model->validate()) {
        $model->dep_id = Yii::$app->user->identity->dep_id;
        $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
 public function actionAddmore(){
         if(\Yii::$app->getRequest()->getIsAjax()) {
        //this is the post data from the ajax request
        $postData = Yii::$app->request->post('Instructions');//var_dump($postData);die;
        if (empty($postData) || !is_array($postData)) {
        throw new HttpException(500, 'An internal server error has occured.');
        }
        $model = array();
        //creating existing model instances + setting attributes
        foreach ($postData as $i => $single) {
        $model[$i] = new Instructions();
        $model[$i]->setAttributes($single);
        }
        $j=$i+1;
        //var_dump($model);die;
        //end of creating existing model instances + setting attributes
        //creating an additional empty model instance
        $model[$j] = new Instructions();
        //var_dump($model);die;
        // it has to be renderAjax in order to include the script validation files
        echo $this->renderAjax('userform',[
        'model' => $model,
        ]);
        // echo $model[0];exit;
        } else {
        throw new HttpException(404, 'Unable to resolve the request: Awards/addmore');
        }
    }

The view files are as follows:

_form.php

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use backend\models\Course;
use dosamigos\tinymce\TinyMce;
/* @var $this yii\web\View */
/* @var $model backend\models\Instructions */
/* @var $form yii\widgets\ActiveForm */
//var_dump($model);die;
?>
    <?php $dataCategory1=ArrayHelper::map(Course::find()->where(['depid'=>Yii::$app->user->identity->dep_id])->asArray()->all(), 'id', 'course_name'); ?>
<div class="instructions-form">
<div id="repeat">
    <?php $form = ActiveForm::begin(); ?>

<?php foreach ($model as $i => $single): ?>
    <div class="row">

    <div style="display:none;" class="col-md-2"><?= $form->field($single, "[$i]dep_id")->textInput() ?></div>

    <div class="col-md-4"><?= $form->field($single, "[$i]course_id")->DropDownList($dataCategory1, 
                $options=['prompt'=>"Select Course",

                    ]) ?></div>

        <div class="col-md-6"><?= $form->field($single, "[$i]instruction")->textArea()?></div>
<div class="col-md-1">
<a href="#"><span class="glyphicon glyphicon-plus-sign" id="but" style="margin-top:30px; color: green; font-size: 1.5em;"></span></a>
<a href="#"><span class="glyphicon glyphicon-minus-sign" id="rem" style="margin-top:30px; color: red; font-size: 1.5em;"></span></a>

<!-- <div class="form-group"><button id="but" class="btn btn-primary">Add</button></div>-->
</div>
</div>

 <?php endforeach; ?>
 <span style="display: none" id="ide"><?php echo $i;?></span>

    <div class="form-group">
        <?= Html::submitButton('Submit' ,['class'=>'btn btn-success']) ?>
    </div>

    <?php ActiveForm::end(); ?>
</div>
</div>
<?php
$this->registerJs("
$(document).on('click', '#but', function(){
$.ajax({
url: '" . \Yii::$app->urlManager->createUrl(['instructions/addmore']) . "',
type :'POST',
cache : false,
data: $('#" . $form->id . "').serialize(),
success: function(data) {
document.getElementById('repeat').innerHTML = data;
},
error: function() {
alert('An error has occured while adding a new block.');
}
});
});
$(document).on('click', '#rem', function(){
var count = document.getElementById('ide').innerHTML;
if(count == 0){
document.getElementById('ide').innerHTML = 0;
alert('One Row should be present in Table');
}
else{
$(this).closest('.block').remove();
count--;
document.getElementById('ide').innerHTML = count;
}
});
");
?>

userform.php

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use backend\models\Course;
use dosamigos\tinymce\TinyMce;
/* @var $this yii\web\View */
/* @var $model backend\models\Instructions */
/* @var $form yii\widgets\ActiveForm */
//echo '<pre>';var_export($model);die;
?>

<?php $form = ActiveForm::begin(); ?>
if (!empty($model)) {
<?php foreach ( $model as $i => $value){ ?>
    <div class="row">

    <div style="display:none;" class="col-md-2"><?= $form->field($value, "[$i]dep_id")->textInput() ?></div>

    <div class="col-md-4"><?= $form->field($value, "[$i]course_id")->DropDownList($dataCategory1, 
                $options=['prompt'=>"Select Course",

                    ]) ?></div>

        <div class="col-md-6"><?= $form->field($value, "[$i]instruction")->textArea()?></div>
<div class="col-md-1">
<a href="#"><span class="glyphicon glyphicon-plus-sign" id="but" style="margin-top:30px; color: green; font-size: 1.5em;"></span></a>
<a href="#"><span class="glyphicon glyphicon-minus-sign" id="rem" style="margin-top:30px; color: red; font-size: 1.5em;"></span></a>

<!-- <div class="form-group"><button id="but" class="btn btn-primary">Add</button></div>-->
</div>
</div>

 <?php } ?>
 <span style="display: none" id="ide"><?php echo $i;?></span>

    <div class="form-group">
        <?= Html::submitButton('Submit' ,['class'=>'btn btn-success']) ?>
    </div>
}
    <?php ActiveForm::end(); ?>

here is the stack trace:
PHP Warning 'yii\base\ErrorException' with message 'Invalid argument supplied for foreach()' 

in /Applications/AMPPS/www/pgserver2015/vendor/yiisoft/yii2/helpers/BaseHtml.php:1602

Stack trace:
#0 /Applications/AMPPS/www/pgserver2015/vendor/yiisoft/yii2/helpers/BaseHtml.php(1602): yii\base\ErrorHandler->handleError(2, 'Invalid argumen...', '/Applications/A...', 1602, Array)
#1 /Applications/AMPPS/www/pgserver2015/vendor/yiisoft/yii2/helpers/BaseHtml.php(757): yii\helpers\BaseHtml::renderSelectOptions('12', NULL, Array)
#2 /Applications/AMPPS/www/pgserver2015/vendor/yiisoft/yii2/helpers/BaseHtml.php(1562): yii\helpers\BaseHtml::dropDownList('Instructions[0]...', '12', NULL, Array)
#3 /Applications/AMPPS/www/pgserver2015/vendor/yiisoft/yii2/helpers/BaseHtml.php(1411): yii\helpers\BaseHtml::activeListInput('dropDownList', Object(backend\models\Instructions), '[0]course_id', NULL, Array)
#4 /Applications/AMPPS/www/pgserver2015/vendor/yiisoft/yii2/widgets/ActiveField.php(580): yii\helpers\BaseHtml::activeDropDownList(Object(backend\models\Instructions), '[0]course_id', NULL, Array)
#5 /Applications/AMPPS/www/pgserver2015/backend/views/instructions/userform.php(25): yii\widgets\ActiveField->dropDownList(NULL, Array)
#6 /Applications/AMPPS/www/pgserver2015/vendor/yiisoft/yii2/base/View.php(325): require('/Applications/A...')
#7 /Applications/AMPPS/www/pgserver2015/vendor/yiisoft/yii2/base/View.php(247): yii\base\View->renderPhpFile('/Applications/A...', Array)
#8 /Applications/AMPPS/www/pgserver2015/vendor/yiisoft/yii2/web/View.php(210): yii\base\View->renderFile('/Applications/A...', Array, Object(backend\controllers\InstructionsController))
#9 /Applications/AMPPS/www/pgserver2015/vendor/yiisoft/yii2/web/Controller.php(47): yii\web\View->renderAjax('userform', Array, Object(backend\controllers\InstructionsController))
#10 /Applications/AMPPS/www/pgserver2015/backend/controllers/InstructionsController.php(161): yii\web\Controller->renderAjax('userform', Array)
#11 [internal function]: backend\controllers\InstructionsController->actionAddmore()
#12 /Applications/AMPPS/www/pgserver2015/vendor/yiisoft/yii2/base/InlineAction.php(55): call_user_func_array(Array, Array)
#13 /Applications/AMPPS/www/pgserver2015/vendor/yiisoft/yii2/base/Controller.php(151): yii\base\InlineAction->runWithParams(Array)
#14 /Applications/AMPPS/www/pgserver2015/vendor/yiisoft/yii2/base/Module.php(455): yii\base\Controller->runAction('addmore', Array)
#15 /Applications/AMPPS/www/pgserver2015/vendor/yiisoft/yii2/web/Application.php(83): yii\base\Module->runAction('instructions/ad...', Array)
#16 /Applications/AMPPS/www/pgserver2015/vendor/yiisoft/yii2/base/Application.php(375): yii\web\Application->handleRequest(Object(yii\web\Request))
#17 /Applications/AMPPS/www/pgserver2015/backend/web/index.php(18): yii\base\Application->run()
#18 {main}
usualdesigner commented 9 years ago

These code looks horrible. Use code tags pls.

fernandezekiel commented 9 years ago

good lord

mdmunir commented 9 years ago

First, read this https://guides.github.com/features/mastering-markdown/ before posting. Second, i am not sure about your issue content (isn't readable for me). But, if you want to asking, use Yii forum or Yii FB Page

ianfranco1986 commented 8 years ago

And nobody answer ...

yii-bot commented 8 years ago

This is an automated comment, triggered by adding the label question.

Please note, that the GitHub Issue Tracker is for bug reports and feature requests only.

We are happy to help you on the support forum, on IRC (#yii on freenode), or Gitter.

Please use one of the above mentioned resources to discuss the problem. If the result of the discussion turns out that there really is a bug in the framework, feel free to come back and provide information on how to reproduce the issue. This issue will be closed for now.