How to use different model from the controller? - php

I am trying to insert record using Cakephp.My model name is something like User.php.
And My working controller name is SignupsController.I want to insert record using this two but I cant.I am give my some codes below :
View :
<?php echo $this->Form->create('Signups',array('action' => 'registration'));?>
<div class="row-fluid">
<div class="span5">
<label class="">*First Name</label>
<?php echo $this->Form->input('first_name', array('type' => 'text','label' => false, 'class' => 'input-xlarge validate[required]', 'div' => false)); ?>
</div>
<div class="span5">
<label class="">*Last Name</label>
<?php echo $this->Form->input('last_name', array('type' => 'text', 'label' => false, 'class' => 'input-xlarge validate[required]', 'div' => false)); ?>
</div>
</div>
<?php echo $this->Form->end(); ?>
My controller code is given below :
class SignupsController extends AppController {
var $name = 'Signups';
var $uses=array("User");
public function registration()
{
$this->layout="reserved";
$this->Club->create();
if (isset($_POST['registration'])) {
echo "This is";
echo "<pre>";print_r($this->request->data);echo"</pre>";
$this->User->save($this->request->data);
//$this->Session->setFlash(__('Promoter registration has been done successfully'));
//$this->redirect('registration');
//$this->redirect(array('action' => 'registration'));
}
}
}
My model name is different which's name is User.php
I want to insert the record using this above code.Any idea how to insert?

you can do this by loading the users model in current controller just write the following line
$this->loadModel('Name of the Model').
then
$this->nameofmodel->save()
As you are unable to understand see this
Controller::loadModel(string $modelClass, mixed $id)¶
The loadModel() function comes handy when you need to use a model which is not the controller’s default model or its associated model:
$this->loadModel('Article');
$recentArticles = $this->Article->find(
'all',
array('limit' => 5, 'order' => 'Article.created DESC')
);
$this->loadModel('User', 2);
$user = $this->User->read();
Above pasted code is taken from CookBook of Cakephp, if you still do not understand just read it it has complete detailed explanation you can also see this to understand

you can use it with $uses variable in SignupController
class SingupController extends AppController
{
public $uses = array('User');
//rest of stuff
}
Or, if you want, you can load it on-demand inside a method:
$this->loadModel('User'); //now model is loaded inside controller and used via $this->User
EDIT: Your data array has to include the name of the model you're saving. So, replace:
$this->Form->create('Signups',array('action' => 'registration')
with:
$this->Form->create('User',array('url' => array('controller' => 'signups', 'action' => 'registration'));

Related

Codeigniter: How to use form_open() in multiple view files

I am trying to get users to fill in much information so I need more than one form and page. I made a main_view.php which has a side bar on the left with links to sub1.php, sub2.php, sub3.php. On the right half of main_view.php, it displays the sub pages with corresponding forms. Part of the main_view.php looks like this:
<?php $view_path = "../../application/views/"?>
<span id="theFormChanger" >
<?php
?>
</span>
var currentPage = 0;
var subviews = ['sub1.php', 'sub2.php','sub3.php'];
$('#sub1').click(function(){
currentPage = 1;
$('#theFormChanger').load(viewpath + subviews[currentPage]);
});
Part of the code of sub view pages:
<?php echo form_open('v_controller'); ?>
<?php echo form_input(array( 'type' => 'text', 'id' => 'demail', 'name' =>'demail')); ?>
<?php echo form_input(array( 'type' => 'text', 'id' => 'dname', 'name' => 'dname')); ?>
<?php echo form_submit(array('id' => 'submit', 'value' => 'Submit')); ?>
<?php echo form_close(); ?>
For ../application/controllers/,there is a v_controller.php:
function __construct() {
parent::__construct();
}
public function index()
{
$this->load->helper('form');
$this->load->view('sub1');
$data = array(
'User_Name' => $this->input->post('dname'),
'User_Email' => $this->input->post('demail'));
}?>
Every time when I go to localhost:8000/main/main_view, the left part is fine but the right part says "Fatal error: Call to undefined function form_open() in main_view.php"
I searched around but couldn't find answers. I made sure everything is loaded in autoload.php.
Is this a routing problem? I can't directly go to view files? Please help me. Thank you!
You can load views on to a view file like so
application > views > default.php
<?php $this->load->view('template/common/header');?>
<?php $this->load->view('template/common/navbar');?>
<?php $this->load->view('template/' . $page);?>
<?php $this->load->view('template/common/footer');?>
And then on controller
<?php
class Example extends CI_Controller {
public function index() {
$data['page'] = 'common/example';
$this->load->view('default', $data);
}
}
you need to create NameOfController/NameOfMethod in the form open method in your view page.
replace our code by this one , it will be work for you.
<?php echo form_open('v_controller/index'); ?>

How to create a Yii2 model without a database

I would like to create a yii2 model without a database. Instead, the data is generated dynamically and not stored, just displayed to the user as a json. Basically, I would just like a get a simple, basic example of a non-database Model working but I can't find any documentation on it.
So how would I write a model without a database? I have extended \yii\base\Model but I get the following error message:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<name>PHP Fatal Error</name>
<message>Call to undefined method my\app\models\Test::find()</message>
<code>1</code>
<type>yii\base\ErrorException</type>
<file>/my/app/vendor/yiisoft/yii2/rest/IndexAction.php</file>
<line>61</line>
<stack-trace>
<item>#0 [internal function]: yii\base\ErrorHandler->handleFatalError()</item>
<item>#1 {main}</item>
</stack-trace>
</response>
To implement find(), I must return a database query object.
My Model is completely blank, I'm just looking for a simple example to understand the principal.
<?php
namespace my\app\models;
class Test extends \yii\base\Model{
}
This is a Model from one of my projects. This Model is not connected with any database.
<?php
/**
* Created by PhpStorm.
* User: Abhimanyu
* Date: 18-02-2015
* Time: 22:07
*/
namespace backend\models;
use yii\base\Model;
class BasicSettingForm extends Model
{
public $appName;
public $appBackendTheme;
public $appFrontendTheme;
public $cacheClass;
public $appTour;
public function rules()
{
return [
// Application Name
['appName', 'required'],
['appName', 'string', 'max' => 150],
// Application Backend Theme
['appBackendTheme', 'required'],
// Application Frontend Theme
['appFrontendTheme', 'required'],
// Cache Class
['cacheClass', 'required'],
['cacheClass', 'string', 'max' => 128],
// Application Tour
['appTour', 'boolean']
];
}
public function attributeLabels()
{
return [
'appName' => 'Application Name',
'appFrontendTheme' => 'Frontend Theme',
'appBackendTheme' => 'Backend Theme',
'cacheClass' => 'Cache Class',
'appTour' => 'Show introduction tour for new users'
];
}
}
Use this Model like any other.
e.g. view.php:
<?php
/**
* Created by PhpStorm.
* User: Abhimanyu
* Date: 18-02-2015
* Time: 16:47
*/
use abhimanyu\installer\helpers\enums\Configuration as Enum;
use yii\caching\DbCache;
use yii\caching\FileCache;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/** #var $this \yii\web\View */
/** #var $model \backend\models\BasicSettingForm */
/** #var $themes */
$this->title = 'Basic Settings - ' . Yii::$app->name;
?>
<div class="panel panel-default">
<div class="panel-heading">Basic Settings</div>
<div class="panel-body">
<?= $this->render('/alert') ?>
<?php $form = ActiveForm::begin([
'id' => 'basic-setting-form',
'enableAjaxValidation' => FALSE,
]); ?>
<h4>Application Settings</h4>
<div class="form-group">
<?= $form->field($model, 'appName')->textInput([
'value' => Yii::$app->config->get(
Enum::APP_NAME, 'Starter Kit'),
'autofocus' => TRUE,
'autocomplete' => 'off'
])
?>
</div>
<hr/>
<h4>Theme Settings</h4>
<div class="form-group">
<?= $form->field($model, 'appBackendTheme')->dropDownList($themes, [
'class' => 'form-control',
'options' => [
Yii::$app->config->get(Enum::APP_BACKEND_THEME, 'yeti') => ['selected ' => TRUE]
]
]) ?>
</div>
<div class="form-group">
<?= $form->field($model, 'appFrontendTheme')->dropDownList($themes, [
'class' => 'form-control',
'options' => [
Yii::$app->config->get(Enum::APP_FRONTEND_THEME, 'readable') => ['selected ' => TRUE]
]
]) ?>
</div>
<hr/>
<h4>Cache Setting</h4>
<div class="form-group">
<?= $form->field($model, 'cacheClass')->dropDownList(
[
FileCache::className() => 'File Cache',
DbCache::className() => 'Db Cache'
],
[
'class' => 'form-control',
'options' => [
Yii::$app->config->get(Enum::CACHE_CLASS, FileCache::className()) => ['selected ' => TRUE]
]
]) ?>
</div>
<hr/>
<h4>Introduction Tour</h4>
<div class="form-group">
<div class="checkbox">
<?= $form->field($model, 'appTour')->checkbox() ?>
</div>
</div>
<?= Html::submitButton('Save', ['class' => 'btn btn-primary']) ?>
<?php $form::end(); ?>
</div>
The reason for using a model is to perform some kind of logic on data that you are getting from somewhere. A model can be used to perform data validation, return properties of the model and their labels, and allows for massive assignment. If you don't need these features for your data model, then don't use a model!
If you are not requiring data validation (i.e. you are not changing any data via forms or other external source), and you are not requiring access to behaviors or events, then you probably need to just use yii\base\Object. This will give you access to getters and setters for properties of the object, which seems to be all you need.
So your class ends up looking like this. I've included getting data from another model, in case that's what you want to do;
<?php
namespace my\app\models;
use \path\to\some\other\model\to\use\OtherModels;
class Test extends \yii\base\Object{
public function getProperty1(){
return "Whatever you want property1 to be";
}
public function getProperty2(){
return "Whatever you want property2 to be";
}
public function getOtherModels(){
return OtherModels::findAll();
}
}
You would then simply use it like this;
$test = new Test;
echo $test->property1;
foreach ($test->otherModels as $otherModel){
\\Do something
}
The function you have tried to use, find(),is only relevant to a database and so won't be available to your class if you've extended yii\base\Model, yii\base\Component or yii\base\Object, unless you want to define such a function yourself.
A lightweight way to create models without database backend is to use a DynamicModel:
DynamicModel is a model class primarily used to support ad hoc data validation.
Just write in your controller:
$model = new DynamicModel(compact('name', 'email'));
$model->addRule(['name', 'email'], 'string', ['max' => 128])
->addRule('email', 'email')
->validate();
and then pass $model to your view.
A full example can be found in http://www.yiiframework.com/wiki/759/create-form-with-dynamicmodel/.
This is perfect for user input for calling APIs, creating forms on the fly, etc.
As has been pointed out in the comments and other answers, your model needs to extend \yii\db\BaseActiveRecord. That said you can store your json as a nosql database such as MongoDb or in a key-value cache such as Redis instead. Both have Yii implementions: \yii\mongodb\ActiveRecord and \yii\redis\ActiveRecord

How to save input in yii to database

I have this code Im trying to save the content and the title from a form I made..It has an id that autoincrement the id number adds in the database but the title and the content isn't/cant be save in the database. Can you please check my code if I've done something wrong? or what I'm lacking at.
Here is my model ContentForm.php
<?php
class ContentForm extends CActiveRecord{
public $content;
public $title;
public function tableName(){
return 'tbl_content';
}
public function attributeLabels()
{
return array(
'contentid' => 'contentid',
'content' => 'content',
'title' => 'title',
// 'email' => 'Email',
// 'usrtype' => 'Usrtype',
);
}
Here is my view content.php
<div>
<p>User: <a href="viewuserpost">
<?php
echo Yii::app()->session['nameuser'];
?>
</a>
</p>
</div>
<h1>Content</h1>
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'contact-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
?>
Title:
<div class="row">
<?php
echo $form->textfield($model,'title');
?>
</div>
</br>
Body:
<div class="row">
<?php
echo $form->textArea($model,'content',array('rows'=>16,'cols'=>110));
?>
</div>
<div class="row buttons">
<?php
echo CHtml::submitButton($model->isNewRecord? 'Create':'Save');
?>
</div>
<?php $this->endWidget(); ?>
and here is my content action in my sitecontroller.php
public function actionContent(){
$model=new ContentForm;
if(isset($_POST['ContentForm'])) {
$model->attributes=$_POST['ContentForm'];
if($model->save())
$this->redirect(array('content','contentid'=>$model->contentid));
$this->redirect(array('content','title'=>$model->title));
$this->redirect(array('content','content'=>$model->content));
}
$this->render('content',array('model'=>$model));
}
Please help.
Remove
public $content;
public $title;
from your class.
Yii uses PHP magic methods. And when you add attributes to your class, PHP doesn't call them but references to your explicitly written attributes.
Moreover, you should add some validation, if you use $model->attributes=$_POST['ContentForm'];. Another variant is to use unsecure $model->setAttributes($_POST[ContentForm], false) where false tells Yii to set all attributes, not only that are considered safe.
Note, that attributes is not real Model attribute, this is virtual attribute accessed through magic methods.
Also, you don't need three redirects. This is HTTP redirect to other page. This time, you just should just specify route to model view action and its parameter that is id, for example. Like this $this->redirect(array('content/view','id'=>$model->contentid));.
Of course, simplest way for you is to create new model and controller with actions using Gii.
you may missed rules , add this in your model ContentForm.php
public function rules()
{
return array(
array('content,title', 'safe'),
);
}
For more about model validation
http://www.yiiframework.com/wiki/56/reference-model-rules-validation/

Having Issues Invoking Actions Of Controller On Button Click

I'm having a problem calling an action in a controller upon button click. So the controller is generated by Gii. All of its actions are the default ones generated by Gii, except for the actionCreate().
Here is the relevant code ::
class ProductsController extends Controller {
public function actionCreate() {
$model = new Products;
if (isset($_POST['params'])) {
// $model->attributes = $_POST['Products'];
//if ($model->save())
// $this->redirect(array('view', 'id' => $model->id));
echo 'Yes Working';
}
$this->render('create', array(
'model' => $model,
));
}
As its clear from the above code snippet this action is calling the view named create.php.
Here is create.php::
<div class="page">
<div class="container">
<div class="row">
<h2>Create Products</h2>
<?php echo $this->renderPartial('_form', array('model' => $model)); ?>
</div>
</div>
And here is the partially rendered form.
<?php
$form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id' => 'products-form',
'action' => Yii::app()->createUrl('products/create'),
'enableAjaxValidation' => false,
));
?>
<div class="form-actions">
<?php
echo CHtml::submitButton('Create', array(
'submit' => 'EasyAesthetics/index.php/products/create',
'params' => '1'
));
?>
</div>
<?php $this->endWidget(); ?>
Now what I want is that upon clicking the button 'Create', it would call the actionCreate() method in the ProductsController. Right now the button is working and I'm being redirected to /demoProject/index.php/products/create, but the echo 'Yes Working' is not displaying.
Can anyone please show me how to achieve this. How can i invoke the create action again with just a button and just a 1 in the $_POST array.
I need to do this so that on clicking create the actionCreate() method will call the relevant components to create the necessary products.
if your "var_dump()"ed your "$_POST" , you would see sensorario answer.
and also you can set your froms send method to post if still not sending post.
$form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id' => 'products-form',
'action' => Yii::app()->createUrl('products/create'),
'enableAjaxValidation' => false,
'method' => 'post',
));
?>
or get your parameter like this(this sets by $_REQUEST):
$param = Yii::app()->request->getParam('Products' , null);
Take a look at the code generated by your form. When you have model called "Hello" with a field called "world", your form field will be
<input type="text" name="Hello[world]">
Try to change your action in this way:
class ProductsController extends Controller {
public function actionCreate() {
$model = new Products;
if (isset($_POST['Products'])) {
echo 'Yes Working';
}
$this->render('create', array(
'model' => $model,
));
}
}
Pay particular attention to these two lines:
$model = new Products;
if (isset($_POST['Products'])) {
Fields will takes the same name of model. In case of more models:
<input type="text" name="Model1[field1]">
<input type="text" name="Model1[field2]">
<input type="text" name="Model21[field2]">
<input type="text" name="Model2[field2]">
and so on ...

insert query is not working in cake php

this is action url: http://localhost/carsdirectory/users/dashboard.
dashboad.ctp (i have select filed and in this select field i m fetching data from that filed car_type and table name car_types)
<?php echo $this->Form->create('User', array('type' => 'file', 'action' => 'dashboard')); ?>
<label class="ls-details-label">Type</label>
<div class="ls-details-box">
<?php
foreach ($car_types as $car_type)
{
$car_type_new[$car_type['Car_type']['id']]=
$car_type['Car_type']['car_type'];
}
echo $this->Form->input('car_type',
array( 'label'=>false,
'options'=>$car_type_new,
'empty'=>' Select ',
'class'=>'styledselect_form_1'));
?>
</div>
<?php echo $this->Form->end(array('label' => 'Submit',
'name' => 'Submit',
'div' => array('class' => 'ls-submit')));?>
users_controller.php (controller)
class UsersController extends AppController{
var $name = "Users";
public function dashboard(){
$this->loadModel('Car_type'); // your Model name => Car_type
$this->set('car_types', $this->Car_type->find('all'));
if(!empty($this->data))
{
$this->loadModel('Car');
if($this->Car->save($this->data))
{
$this->Session->setFlash('Detail has Been Saved');
$this->redirect(array('action'=>'dashboard'));
}
else
{
$this->Session->setFlash('Detail could not save');
}
}
}
car.php (model)
<?php
class Car extends appModel{
var $name = "Car";
}
?>
i want to inset data car_type_id field in (table name cars) , but i m not able to do it
so plz help me
thanks in advance, vikas tyagi
You may try this:
echo $this->Form->input('Car.car_type_id', array(...));

Categories