tags:

views:

3620

answers:

4

Can I use another Model inside one model?

Eg.

  <?php
  class Form extends AppModel
  {
      var $name='Form';
      var $helpers=array('Html','Ajax','Javascript','Form');
      var $components = array( 'RequestHandler','Email');

      function saveFormName($data)
      {
          $this->data['Form']['formname']=$data['Form']['formname'];
          $this->saveField('name',$this->data['Form']['formname']);
      } 

      function saveFieldname($data)
      {
          $this->data['Attribute']['fieldname']=$data['Attribute']['fieldname'];
      }

   }
   ?>
+5  A: 

You can create instances of other models from within any model/controller using one of these two methods.

If you're using Cake 1.2:

App::import('model','Attribute');
$attr = new Attribute();
$attr->save($dataYouWantToSavetoAttribute);

If you're using Cake 1.1:

loadModel('Attribute');
$attr = new Attribute();
$attr->save($dataYouWantToSavetoAttribute);
inkedmn
App::import() is not very good for models. $attr = ClassRegistry::init('Attribute') should be used.
dr Hannibal Lecter
Actually my form has fields(Attributes) like associations
Aruna
@dr Hannibal Lecter: Why it is not good for models?
bancer
+2  A: 

In cakephp 1.2 it's better to use:

Classregistry::init('Attribute')->save($data);

michas
A: 

Should be a comment on michas's answer, but I can't comment....

Why is it better in Cakephp 1.2 to use Classregistry::init('Attribute')->save() etc...?

CrayFishUK
A: 

I feel this way Classregistry::init('Attribute') is simple to use,and it return the instance of Attribute.

chris