Search code examples
modeldataprovideryii

Need some help understanding model and dataprovider


I am new to Yii and am trying to understand it by creating a hobby web site to manage my food shopping. I am trying to create a page which lists my recipes and has a +/- button next to each recipe which when pressed updates a shopping list on the same page. All of the recipe ingredients and the shopping list is stored in an SQL database.

So far, I have a controller called ShoppingListController and in my actionIndex() function (which shows the recipes and shopping list) I am creating two dataproviders and a model (for the +/- buttons which are a form) and passing them to my view as follows:

        // Create a shopping list item model
        $shoppingListModel = new TblShoppingListItem;

        // Get the saved shopping list data from the shopping list table
        $shoppingDataProvider = new CActiveDataProvider('TblShoppingListItem', array(
            'criteria'=>array(
                'select'=>array('recipe_id', 'recipe_multiplier')), 
            'pagination'=>array('pageSize'=>500)
        ));

        // Get the recipe ingredient data from the recipe models and order by recipe name           
        $recipeDataProvider = new CActiveDataProvider('TblRecipeIngredient', array(
            'criteria'=>array(
                'select'=>array('recipe_id', 'ingredient_id', 'ingredient_unit_id', 'ingredient_amount'),   
                'with'=>array('recipe','ingredient','ingredientUnit'),
                'together'=>true,
                'order'=>'recipe.name ASC'),
            'pagination'=>array('pageSize'=>500)
        ));

        // Render the 'shoppinglist/show' page
        $this->render('show', array(
            'recipeDataProvider'=>$recipeDataProvider, 
            'shoppingDataProvider'=>$shoppingDataProvider,
            'shoppingListModel'=>$shoppingListModel
        ));

I am a bit confused - I seem to need the model to pass into the +/- forms, I need the first data provider so I can display my shopping list and I need the second data provider so that I can display my recipe information.

However, I am wondering do I actually need the shoppingListModel and the shoppingDataProvider (i.e. is having both bad practice)?. Could I get the information I need just from the model?. I am confused by the difference between a model and a data provider.


Solution

  • That is your choice that use or not to use a dataprovider. I am using dataproviders just when I need pagination or a gridview, every other time I just use data from models.

    Dataproviders give additional control options on data, but if you need just data I think you must use models.