How do I import a Model from another Model in CakePHP - php

Desc Model belongsTo Prod Model. I want that all Prod.Name will appear as checkboxes when adding a new desc, so that user will just click a Prod.Name when adding a new description for it. Like:
<?php
echo $form->create('Desc');
echo $form->checkBox(Prod.Name); // assuming this is the correct code.
echo $form->textArea('Desc.content');
echo $form->end('Save');
?>
I'm still not familiar with this framework, still messing with it.
Thanks!
So far this is what I did:
<select name='data[Desc][prod_id]' id='DescriptionProdId'>
<?php echo $form->create('Desc'); ?>
<?php foreach($opps as $opp): ?>
<option value="<?php $opp["Prod"]["id"] ?>">
<?php echo $opp["Prod"]["name"]; ?>
</option>
<?php endforeach; ?>
</select>

Instead of creating the element manually, you should use the FormHelper.
In your view:
<?php
echo $form->input('prod_id', array('options' => $opps));
?>
Cakephp will make the select input, using the $opps records as the options. You can also set other options other than the 'options' option. Check out:
http://book.cakephp.org/view/189/Automagic-Form-Elements
If you specify the view variable as prods in your controller action, then you do not need to specify the options key of the $options array. In the controller action:
$this->set('prods', $this->find('all'));

Related

how to get data from Input Form Cakephp 3

I am very new to this Cakephp framework, trying to follow and understand how to upload files using cakephp. I am using upload plugin provided by josediazgonzalez. In the view file, using formhelper i have:
<?= $this->Form->create($user, ['type' => 'file']) ?>
<fieldset>
<legend><?= __('Add User') ?></legend>
<?php
echo $this->Form->control('name');
echo $this->Form->control('username');
echo $this->Form->control('password');
echo $this->Form->control('role');
echo $this->Form->input('photo', ['type' => 'file']);
echo $this->Form->control('dir');
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
I want to print again the value that i submitted in my controller, what should i write? Something like:
$this->request->data;
$this->request->data is an array of data passed to your scirpt. You can use it to get field that you are interested in with, eg:
$data = $this->request->data;
$someVariable = $data["name"];
Or, you can access any field directly, by using data() accessor:
$someVariable = $this->request->data("name");
From this point, you can do anything you want with this variable.
One more thing - as $this->request->data and $this->request->data() are currently in deprecated state and will be removed in next version, I suggest to use $this->request->getData() instead. Usage is similar:
$this->request->getData(); //will return array of data passed
$this->request->getData("field_name"); //access to specific field

How to send the request through POST and how to access attributes of the model?

I am a bit new to the Yii Framework. I am making a product selling website, which has 3 basic models
1. Users model containing the primary key id
2. Products model containing the primary key id
3. Orders model which is basically a mapping between the products and orders. It contains the fields product_id and user_id as foreign keys.
I have made a page where all the products are populated and the logged in user can click on a button on product box to order a particular product.
the code of the link is like this
<?php echo CHtml::link('Order Now',array('order',
'product_id'=>$model->id,
'user_id'=>Yii::app()->user->id)); ?>
(Q1) This is sending a GET request but I want to sent the details as post request. How to do this?
My default controller is the site controller. I have made an actionOrder method in this controller.
The code is:
if(Yii::app()->user->isGuest){
$this->redirect('login');
}else{
$model=new Orders;
if(isset($_POST['products_id']))
{
$model->attributes->products_id=$_POST['product_id'];
$model->attributes->users_id=Yii::app()->user->id;
if($model->save())
$this->redirect(array('index'));
}
$this->render('index');
}
But this code is showing bunch of errors. Also, (Q2) how can I put both products_id and users_id in a single array Orders so that I just have to write $_POST['orders']
Also, (Q3) how can I display a flash message after the save is successful?
Kindly help me to solve my 3 problems and sorry if you feel that the questions are too stupid.
Q1: If you want to use POST request, you're going to have to use a form of sorts, in this case the CActiveForm.
Controller:
public function actionOrder()
{
if(Yii::app()->user->isGuest)
$this->redirect('login');
else
{
$model=new Orders;
if(isset($_POST['Orders']))
{
$model->product_id=$_POST['Orders']['products_id'];
$model->users_id = Yii::app()->user->id;
if($model->save())
{
// Q3: set the flashmessage
Yii::app()->user->setFlash('ordered','The product has been ordered!');
$this->redirect(array('index'));
}
}
$this->render('index', array('model'=>$model)); //send the orders model to the view
}
}
View:
<!-- Q3: show the flash message if it's set -->
<?php if (Yii::app()->user->hasFlash('ordered')): ?>
<?php echo Yii::app()->user->getFlash('ordered'); ?>
<?php endif ?>
...
<?php $form=$this->beginWidget('CActiveForm', array('id'=>'order-form')); ?>
<?php echo $form->hiddenField($model,'products_id',array('value'=>$product->id)); ?> // please note the change of variable name
<?php echo CHtml::submitButton('Order Now'); ?>
<?php $this->endWidget(); ?>
Please note that I have changed the name of the product model variable $model to $product, because we will be using $model for the Orders model for the form.
Q2: In this case I set the users_id value in the controller, so $_POST['Orders'] only contains the value for products_id. In yii you can also mass assign your attributes with:
$model->attributes = $_POST['Orders']
Which basicly means $_POST['Orders'] is already an associative array containing the attribute names and values that are in your form.
Q3: The code shows you how to set and show a flash message after an order is succesfull.
First you have to declare forms send method, if you're using bootsrap it'll be like mine:
<?php $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'action' => Yii::app()->createUrl($this->route),
'method' => 'post',
'id' => 'activity_timeRpt',
));
?>
Second if you want to send custom inputs, you have to specify, otherwise it'll be like
i'll be back to finish this
For your questions 1 and 2 I'd recomend you to use a CActiveForm class. For example
<?php $form = $this->beginWidget('CActiveForm', array(
'action' => 'you_action_here'
'method'=>'post' // this is optinal parameter, as 'post' is default value
)); ?>
<?php echo $form->textField($model,'product_id'); ?>
<?php echo $form->hiddenField($model,'user_id', array('value'=>Yii::app()->user->id)); ?>
<?php $this->endWidget(); ?>
where $model is instance of Orders class, passed by variables thru controller, or set in view file. After that you can use it in way you wanted $model->attributes = $_POST['orders'] in your action method.
For flash message you can use Yii->app()->user->setFlash('orderStatus', 'Successful'), before redirect( or render ) in your actionOrder. To show it:
<?php if(Yii::app()->user->hasFlash('orderStatus')):?>
<div class="info">
<?php echo Yii::app()->user->getFlash('orderStatus'); ?>
</div>
<?php endif; ?>

How can I add a derived column to my Yii model?

In Yii, I need to add a "derived" column to any resultset from my model. The column doesn't actually exist in the database table.
For example, say I have an Activity model. There are only two types of Activities: (1) Income, or (2) Expense.
If I want to add a column called income_total or expense_total (depending on what type of activity is being accessed), how would I do that?
Here's a working example of an Activity model in Ruby on Rails (I'm basically wondering how to do the same thing, but in Yii):
class Activity < ActiveRecord::Base
attr_accessible :name, :effective_at, :amount, :category
scope :incomes, :conditions => { :category => 'Income' }
scope :expenses, :conditions => { :category => 'Expense' }
def self.incomes_total
incomes.sum :amount
end
def self.expenses_total
expenses.sum :amount
end
end
Update 2012-07-01:
The answer provided by Leonardo points to the use of Virtual Attributes, this adds an attribute to each "row" of the resultset that I'm retrieving from the database.
If the Activity model has a BELONGS_TO relationship with Parent, a Parent View may look like the following:
<h2><?php echo $parent->name; ?></h2>
<ul>
<?php foreach($portfolio->activities as $activity): ?>
<li>
<?php echo CHtml::link($activity->name, array('activity/view', 'id' => $activity->id)); ?>
<?php echo $activity->amount; ?>
<?php echo $activity->incomes_total; ?>
</li>
<?php endforeach; ?>
</ul>
However, it doesn't make sense for this Virtual Attribute to be accessed within the foreach() loop.
These Virtual Attributes that I want provide one "aggregated" value for the whole resultset, so I want to be able access it using $parent->activities->incomes_total, like so:
<h2><?php echo $parent->name; ?></h2>
<?php echo $parent->activities->incomes_total; ?>
<ul>
<?php foreach($portfolio->activities as $activity): ?>
<li>
<?php echo CHtml::link($activity->name, array('activity/view', 'id' => $activity->id)); ?>
<?php echo $activity->amount; ?>
</li>
<?php endforeach; ?>
</ul>
What do I need to do within the Activity model code to achieve this, or should I be thinking about this a different way?
I believe it is pretty similar to Ruby. PHP has magic methods, which in Yii is implemented by CComponent (base class of many including CActiveRecord).
In short you can do this within your model
class Activity extends CActiveRecord {
public function getIncome_Total() {
// ...
}
}
And, to access it from controller
$activity = Activity::model->findByPk(1);
$income_total = $activity->income_total;
As I posted in the other answer You can simply use a stat relation. Specify a STAT relation in Parent model as
'incomes_total'=>array(self::STAT, 'Activity', 'parent_id','select'=>'SUM(amount)','condition'=>"incomes_total.category='Income'")
Similiarly
'expense_total'=>array(self::STAT, 'Activity', 'parent_id','select'=>'SUM(amount)','condition'=>"incomes_total.category='Expense'")
NOTE: Change the attribute names parent_id and amount as in your model
I don't know how this can be done within the model.
Although it is more processing, an option or workaround is to add another foreach() loop to the View like so:
$incomes_total = 0;
foreach($parent->activities as $activity)
$incomes_total += $activity->amount;
echo $incomes_total;

cakephp: get values from a “car_types” table in the “users_controller.php” file?

i have table "car_types" ,a Controller users_controller and action url
localhost/carsdirectory/users/dashboard
in users_controller.php file i used that function
public function dashboard(){
$this->set('users', $this->Car_type->find('all'));
}
i want to retrieve data from car_types and want to show
localhost/carsdirectory/users/dashboard in select box
i m getting those error
Undefined property: UsersController::$Car_type
i know, i am wrong but not able to sort out that problem
plz help me thanks in advance , vikas tyagi
It seems there's no relation between Users & Car_Type, you could do:
$this->loadModel('CarType'); // your Model name => CarType
//then
$this->set('users', $this->CarType->find('all'));
To populate it in selectbox, something like this should work:
<select>
<?php foreach($users as $key => $val) { ?>
<option value="<?php echo $val['CarType']['id']; ?>">
<?php echo $val['CarType']['car_type']; ?>
</option>
<?php } ?>
</select>
Hope it helps

Cakephp Form with Selection of other Model

In Cakephp I have a model called Category and I have another model called Page. Now I connected the Page with $belongsTo to the Category model.
Now I have a form where I can create a new Page:
<?php echo $this->Form->create('Page', array('action' => 'create')); ?>
<?php echo $this->Form->input('title'); ?>
<?php echo $this->Form->input('text'); ?>
<?php echo $this->Form->end('Create new Page'); ?>
Now I want to add the possibility to select the category in the form. I think the solution is simple but I didn't found anything helpful so far...
in your form add this code
echo $this->Form->input('category_id');
now go to your Page controller, inside the appropriate action method, you add this code
$categories = $this->Page->Category->find('list');
$this->set(compact('categories'));

Categories