This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I created dropdown filter, it's display, but don't worked right. As I anderstand trouble in search() method
view:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$model->search(),
'filter' => $model,
'columns'=>array(
array(
'name' => 'client_id',
'filter' => CHtml::listData(Client::model()->findAll(), 'client_id', 'name'),
'value'=>'$data->client->name'
),
'task'
)
));
I have to tables, and they relations are shown down
model:
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'client' => array(self::BELONGS_TO, 'Client', 'client_id'),
);
}
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->with = array('client');
$criteria->compare('task_id',$this->task_id);
$criteria->compare('client_id',$this->client_id);
$criteria->compare('name',$this->client->name);
$criteria->compare('task',$this->task,true);
$criteria->compare('start_date',$this->start_date,true);
$criteria->compare('end_date',$this->end_date,true);
$criteria->compare('complete',$this->complete);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
I anderstand my mistake, my controller should look like this:
public function actionIndex()
{
$model=new Tasks;
if(isset($_REQUEST['Tasks']))
$model->attributes=$_GET['Tasks'];
$this->render('index',array(
'model'=>$model
));
}
I forgout pass parametrs from controller to model. Thx all!
Check rules method. client_id should be in safe for search
public function rules()
{
return array(
array('client_id', 'safe', 'on'=>'search'),
);
}
Check this wiki, it explains exactly what you need in a detailed way.
Related
my question has two parts
Firstly, My if statement is not working. My if statement is as followed:
if ($request->is_published) {
$resources_page->published_at = now();
}
This is stored in my controller, I have a model for this and it is as followed:
public function is_published()
{
return $this->published_at !== null;
}
It is meant to check whether my checkbox is checked and return the timestamp, I have it cast in my model like followed:
protected $casts = [
'published_at' => 'datetime',
];
And in my view:
#include('components.form.input-checkbox', [
'label' => 'Publish?',
'form_object' => 'page',
'name' => 'is_published'
])
Could anyone elude to the answer?
Secondly, when trying to sync, it is not storing to my resources_category_resources_page table
In my controller, i have the following code
$resources_page->resources_categories()->sync(
ResourcesCategory::whereIn('slug', $request->resources_categories)->pluck('id')
);
In my model I have the relationships declared properly, so I don't know why its not storing?
I am trying to allow users to post pictures and comment on pictures. The pictures are related to the users through a one to many relationship and the comments are related to the pictures through a one to many relationship. I am now trying to simultaneously relate both users and pictures to comments whenever a comment is made. Currently, I am able to relate comments to either the picture or the user but not both.
Below is the controller method which handles comment uploads:
public function postComment(Request $request, $picture_id)
{
$this->validate($request, [
"comment" => ['required', 'max:1000'],
]);
$picture = Picture::find($picture_id);
$picture->status()->create([
'body' => $request->input('comment'),
]);
Auth::user()->statuses()->update([
'body' => $request->input('comment'),
]);
return redirect()->back();
}
I have tried creating one relationship and then creating the other relationship using update(). This did not work and resulted in the value remaining null.
Thank you for your help.
If i am understanding your database model correctly, when creating the status model for your picture all you need to do is to also include the user id like so:
public function postComment(Request $request, $picture_id)
{
$this->validate($request, [
"comment" => ['required', 'max:1000'],
]);
$picture = Picture::find($picture_id);
$picture->status()->create([
'body' => $request->input('comment'),
'user_id' => Auth::id()
]);
return redirect()->back();
}
Also make sure to add user_id to the $fillable property in the Status model to allow it to be assigned through the create method
protected $fillable = [
'body', 'user_id',
];
This should link the status you just created to both the picture and user class. You can then retrieve it elsewhere with something like Auth::user()->statuses
How do you validate a field is unique in cakephp 3.0? There doesn't appear to be a validation function listed in the API.
You want to use the rule validateUnique. For example, to check an email address is unique on an UsersTable:-
public function validationDefault(Validator $validator)
{
$validator->add(
'email',
['unique' => [
'rule' => 'validateUnique',
'provider' => 'table',
'message' => 'Not unique']
]
);
return $validator;
}
Details can be found in the API docs.
you have to use the rules from cake's ORM on your table...
add this at the top of your UsersTable after your namespace
use Cake\ORM\Rule\IsUnique;
Then prepare your rule to apply to your field by placing it in a public function
public function buildRules(RulesChecker $rules){
$rules->add($rules->isUnique(['email']));
return $rules;
}
Consult the cakephp documentation for more information about RULES
Validation providers can be objects, or class names. If a class name is used the methods must be static. To use a provider other than ‘default’, be sure to set the provider key in your rule:
// Use a rule from the table provider
$validator->add('title', 'unique', [
'rule' => 'uniqueTitle',
'provider' => 'table'
]);
For more details, look at the Adding Validation Providers section in the CakePHP3 reference book.
Use application rules as described in manual.
Kindly please check this for unique validation in cakephp 3.8
go to site
public function validationDefault(Validator $validator)
{
$validator->requirePresence('login_id');
return $validator;
}
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->isUnique(['login_id'], 'User already exist.'));
return $rules;
}
I haven't been able to find a solution that solves this. I am trying to query my database for a list of groups to which a user belongs. Users can be in multiple groups, and groups can have multiple users.
I have "users", "groups", and "groups_users" tables. Each has an "id" field, and the "groups_users" table has two other fields, "group_id" and "user_id".
I think all the tables are properly formed.
My User.php, and Group.php model files look like this
//app/Model/User.php
class User extends AppModel {
public $recursive = 1;
public #hasAndBelongsToMany = array(
'Group' => array(
'className' => 'Group',
'joinTable' => 'groups_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'group_id'
)
);
}
//app/Model/Group.php
class Group extends AppModel {
public $recursive = 1;
public #hasAndBelongsToMany = array(
'User' => array(
'className' => 'User',
'joinTable' => 'groups_users',
'foreignKey' => 'group_id',
'associationForeignKey' => 'user_id'
)
);
}
Then, in my Controller file I have this
//app/Controller/ProjectController.php
class ProjectController extends AppController {
public $uses = array('Groups', 'Users');
...
$this->set('groupsForUser', $this->Groups->find('all', array(
'conditions' => array('Users.UserName' => 'testuser1')
));
}
Every time I try to display the data, I get the error message
Error: ..... Unknown column 'Users.UserName' in 'where clause'
And it shows me the SQL it's trying to run:
SELECT Groups.id, ... FROM accounts.groups AS Groups WHERE Users.UserName = 'testuser1'
Obviously the association between the tables isn't happening properly and the SQL query it is sending in isn't joined properly, but I can't figure out what's going wrong here. I've tried varieties like
.....$this->Groups->Users->find(....
And stuff like that, but nothing seems to work.
Help!
I think You should use "User.UserName" instead of "Users.UserName" in your ProjectController.php because you have "User" in your associations So model name should be same.
//app/Controller/ProjectController.php
class ProjectController extends AppController {
public $uses = array('Groups', 'User');
...
$this->set('groupsForUser', $this->Groups->find('all', array(
'conditions' => array('User.UserName' => 'testuser1')
));
}
I had to take a completely different approach to the problem. It's mostly "Cake-y".
I simplified the models a bit by taking out the $recursive bit and trimmed down the HABTM part, removing the joinTable, foreignKey, and associationForeignKey bits)
The ProjectController got the code:
public $uses = array('Group', 'User');
$arrayGroupsForUser = array();
....
$results = $this->User->Find('first', array(
'conditions' => array('User.UserName' => 'testuser1')
));
foreach($results['Group'] as $result) {
array_push($arrayGroupsForUser, $result['name']);
}
$this->set('groupsForUser', $arrayGroupsForUser);
(Thank you ned stark for noting the need for a singular "User". I can't upvote your answer with my limited reputation yet.)
The "$this->set(.....);" line is to pass just the array of group names to the View to use.
This link http://rottmann.net/2012/07/cakephp-hasandbelongstomany-relationship-queries-demystified/ was a big help in helping me solve this.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have the following code in model:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Membership_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
public function register_user($info)
{
if(isset($info))
{
$data = array(
'fullname' => $info['fullname'] ,
'mobile' => $info['mobile'] ,
'telephone' => $info['home'] ,
'username' => $info['username'] ,
'password' => $info['password'] ,
'email' => $info['email'] ,
'member_type' => $info['memberType']
);
$this->db->insert('users', $data);
}
}
}
and am calling it this way in controller:
$info = array('fullname' => $fullname , 'mobile' => $mobile, 'home' => $home,
'username' => $username, 'password' => $password,
'memberType' => $memberType, 'email' => $email );
$this->membershipModel->register_user($info);
Nevertheless, I am getting this error:
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Membership::$db
Filename: core/Model.php
Line Number: 51
Any idea what that means? regards,
In CodeIgniter, class and method names are case sensitive:
$this->membershipModel->register_user($info);
should read...
$this->Membership_model->register_user($info);
NOTE
Make sure you name your model file as: membership_model.php as specified in the CodeIgniter documentation.