creation of model object in controller yii - yii

can any one tell me how to create a model object inside a constructor in yii. I had written the code as belo
<?php
class DistributorsController extends Controller
{
public $layout = '//layouts/column4';
public $defaultAction = null;
public function __construct()
{
echo '<br>Into constructor';
parent::__construct('Distributors','distributors');
}
public function actionDistributors()
{
$this->render("ChannelMask");
}
}
?>
But it is displaying only "Into constructor" string and view is not showing in my browser.

You need to call a model into the Controller.
Create a model, then in Controller, call it like :
Distributor::model()->findAll($criteria); //many models
or
Distributor::model()->findById($id); // one model

Like any other place if you want to create a new model:
$model = new Distributors();
or
$model = $this->loadModel($id, 'Distributors');
if you want to populate your model with existing data, then:
$model = Distributor::model()->findAll(); // all there is
or
$model = Distributor::model()->findByPk($id); // find by primary key

Related

Associate method in laravel 8

I'm new to laravel and I'm making a small api with just two tables to start. I have roles and people. I want to assign a role to a person from the store method but I don't understand how associate() works or how to implement it in the store method, this is what i have;
Model Rol:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
use HasFactory;
protected $fillable = ['id', 'rol'];
public function personas()
{
return $this->hasMany(Persona::class);
}
}
Model Persona:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Role;
class Persona extends Model
{
use HasFactory;
protected $fillable = ['id', 'nombres', 'apellidos', 'rol_id'];
public function rol()
{
return $this->belongsTo(Role::class, 'rol_id');
}
}
$rol = Role::find(1);
$persona->rol()->associate($rol);
$persona->save();
Persona controller store method:
public function index()
{
return PersonaResource::collection(Persona::with('rol')->paginate(25));
}
public function store(Request $request)
{
//$rol = Role::find(1);
$persona = new Persona();
// datos que voy a guardar
$persona->nombres = $request->nombres;
$persona->apellidos = $request->apellidos;
$rol = new Role();
//$rol->personas()->save($rol);
$persona->rol()->save($rol);
}
I want to know how to correctly associate both models to be able to correctly save the related data

MVC view model to stored procedure

How to assign stored procedure result to a view model class in MVC 4?
We are CRUD operations in a single view
VMClinics vc = new VMClinics();
var clns= db.USP_GLOBAL_SELECT_CLINICS_WITH_UNIT_ID(id);
return PartialView("_CreateClinics",vclns);
Add a property of Type IEnumerable in VMClinics model.
public class VMClinics
{
public IEnumerable<ListOfClinics> listOfClinics {get;set;}
}
In your controller
public ActionResult Index()
{
VMClinics vc = new VMClinics() { listOfClinics=db.USP_GLOBAL_SELECT_CLINICS_WITH_UNIT_ID(id).ToList()};
return PartialView("_CreateClinics",vclns);
}

Adding a dropdownlist in MVC

If MVC only allows you to have one ViewModel per View, how does one incorporate a dropdownlist (need to have a separate ViewModel for this) into an existing View which is already used by another ViewModel (ie an entity which has a column for this dropdownlist)?
This Question in addition, I guess, Got everything you are looking for:
How to write a simple Html.DropDownListFor()?
As a beginner, I did a very basic implementation of dropDownlist using the NorthWind Database only.
I had imported the Product & Suppliers table from Northwind database.
In the ProductController.cs file, which is the controller file for my Product table, add method: GetAllSuppliers to get all SuppliersID which we will display in a dropdown.
public IEnumerable<int> GetAllSuppliers()
{
NorthwindEntities db = new NorthwindEntities();
return db.Suppliers.Select(e => e.SupplierID);
}
Now, in the Create action method in ProductController.cs, pass all the values of SupplierID in ViewData as seen below:
public ActionResult Create()
{
ViewData["Suppliers"] = new SelectList(GetAllSuppliers());
return View(new Product());
}
In your corresponding Create.aspx View, use this:
<%: Html.DropDownListFor(model => model.SupplierID, ViewData["Suppliers"] as SelectList) %>
Below is a snapshot of the Result:
Let me know if you need any explanation.
You can make a property inside your main ViewModel which contains ViewModel for dropdownlist and use it with dropdown.
Assume you have controller.
public class HomeController
{
public ActionResult Index()
{
var viewModel = new MainViewModel
{
SomeProperty = "SomeValue",
DropDownData = new DropDownDataViewModel() // Initialize it with appropriate data here.
};
return this.View(viewModel);
}
}
And MainViewModel
public class MainViewModel
{
public string SomeProperty {get; set;}
public DropDownDataViewModel DropDownData { get; set; }
}
So, inside your view you can call #Model.DropDownData to get access to this viewmmodel.

cakephp override construct in child controller

I'm wondering if it is possible to inherit/override constructors in child controllers in cakephp.
In my AppController.php
I have it like this:
public function __construct( $request = null, $response = null ) {
parent::__construct( $request, $response );
$this->email = new CakeEmail();
$this->_constants = array();
$this->_constants['some_var'] = $this->Model->find( 'list', array(
'fields' => array( 'Model.name', 'Model.id' )
) );
}
and in my child controller SomeController.php, it inherits the parent constructor
public function __construct( $request = null, $response = null ) {
parent::__construct( $request, $response );
}
and when I tried to access $this->email and $this->_constants['some_var'] they both are null. But as soon as I put the code directly in SomeController.php instead of inheriting, it worked.
Did I do something wrong or this is simply not approachable for cake?
Also I tried the same with function beforeFilter(), same thing happened.
But it makes sense that each controller to have its own beforeFilter().
I wouldn't even try overriding the _construct' function of the appController. That's what thebeforeFilter,beforeRender` methods are for. It looks like you are just trying to pass vars to each controller from the appController. You can do that like so...
class AppController extends Controller {
var $_constants = array();
public function beforeFilter(){
$this->_constants[] = array('this', 'that', 'the other');
}
}
and in your model's controller you can access the variable like so...
class UsersController extends AppController {
public function add(){
pr($this->_constants);
}
}
It's a different story if you are trying to send the variables to the view (slightly). Just use the set method
class AppController extends Controller {
public function beforeFilter(){
$this->set('_constants', array('this', 'that', 'the other'));
}
}
and in any view you can just call the _constants variable with pr($_constants);. Because it is in the appController it should be available on every view.

Problem in Creating Simple Form in Zend

I am new on Zend Framwork(MVC). I want to crate simple a Form with some HTML control.
I have create one controller IndexController, code are as follows:
<?php
class IndexController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
// action body
/*$this->view->var = 'User Login Page';*/
$form = new Form_Login();
$this->view->form=$form;
}
}
And my Form's code in application/forms/Login.php:
<?php
require_once('Zend/Form.php');
class Form_Login extends Zend_Form
{
public function init()
{
parent::__construct($options);
// the code bellow will create element
$username = $this->CreateElement('text','username');
$username->setLabel("Username:");
// and
$submit= $this->CreateElement("submit","submit");
$submit->setLabel("Submit");
// now add elements to the form as
$this->addElements(array(
$username,
$submit
));
}
}
?>
When i run this project then its show an error like this:
**Fatal error: Class 'Form_Login' not found in C:\xampp\htdocs\LoginForm\application\controllers\IndexController.php on line 16**
Please help me...
Thanks
Pankaj
Everything looks good, make sure your Login.php file has this as the first lines:
<?php
class Form_Login extends Zend_Form
{
public function init()
If that doesn't help, you might want to check your index.php/Bootstrap.php files and server configuration to make sure all paths are correct.