I am trying to create a form which will have multiple fields , some fields will be filled by user and others will be dump into database as defined .
I really do not know how to work with this in term of syntax.
To be more Generic , For Example I have Post tble which have following fileds
id' => 'ID',
'post_head' => 'Heading',
'post_desc' => 'Description',
'post_tags' => 'Tags',
'created_time' => 'Created Time',
'created_date' => 'Created Date',
'post_image' => 'Upload Image',
'post_status' => 'Status',
'user_id' => 'User',
'category_id' => 'Category',
);
Now I want to take input from user in the following fields only :
Heading
Description
Tags
Upload Image
Now I want to know that How can I
pass current time and current date in database field without user
input. user id from session
In your model:
function beforeSave() {
if($this->getIsNewRecord()) {
$this->created_date = new CDbExpression('NOW()');
$this->created_time = new CDbExpression('NOW()');
}
$this->user_id = Yii::app()->user->id;
return parent::beforeSave();
}
1) If the you use database like MySQL you don't need created_date and created_time, just a datetime field (probably created_time is such), which will store both data!
public function behaviors()
{
return array(
'CTimestampBehavior' => array(
'class' => 'zii.behaviors.CTimestampBehavior',
'updateAttribute' => false,
'createAttribute' => 'created_time',
)
);
}
Then for two:
function beforeSave() {
if (!parent::beforeSave) {
return false;
}
$this->user_id = Yii::app()->user->id; // it should be this one, but it depends on how you implemented logging!
return true;
}
Instead of
'created_time' => 'Created Time',
'created_date' => 'Created Date',
You need just one field in your database:
create_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
Many of php functions use timestamp, it's very easy to use it. You can read here.
So if you insert NULL create_time, mysql will insert default value DEFAULT CURRENT_TIMESTAMP - current time.
As said #Veseliq and #mashingan you need to add
function beforeSave() {
$this->user_id = Yii::app()->user->id;
return parent::beforeSave();
}
or try to add in your form view:
echo $form->hiddenField($model, 'user_id', array('value'=>Yii::app()->user->id));
If it doesn't work, show us var_dump(Yii::app()->user->id);
Related
This question is a follow-up of this one How to properly insert time when user leaves( user_left and user_joined got the same value)
I get data when user logged in and store in in DB.
Broadcast::channel('chat', function ($user) {
$ip = Request::ip();
$time = now();
if (auth()->check() && !session()->has('name')) {
UserInfo::storeUser();
session()->put('name',$user->name);
return [
'user_id' => $user->id,
'ip' => $ip,
'name' => $user->name,
'joined' => $time,
];
}
});
I get time when user logged out and also store in DB.
public function logout() {
$info = auth()->user()->info;
$info->left = now();
$info->save();
auth()->logout();
session()->forget('name');
session()->put('left', now());
return redirect('/');
}
UserInfo model
public static function storeUser() {
UserInfo::create([
'user_id' => Auth::id(),
'ip' => Request::ip(),
'name' => Auth::user()->name,
'joined' => now(),
]);
}
This is what I've got.
The time when user left gets inserted not in the way I would like to. The first record with the name of the current user gets the time. I would like to see the LAST record of the current user receiving that data(when Syd 12 logged out Syd 10 received Syd's 12 'left' data. The same story goes with Kate.)
Hi all today i have this problem with my api.
I don't update the record on DB.
In postaman the response is true but don.t save in db.
In Postaman i passed with PUT method and set in Body name a text
ProductController:
public function update(Request $request, $id)
{
$product = auth()->user()->products()->find($id);
if (!$product) {
return response()->json([
'success' => false,
'message' => 'Product with id ' . $id . ' not found'
], 400);
}
$updated = $product->fill($request->all())->save();
if ($updated)
return response()->json([
'success' => true
]);
else
return response()->json([
'success' => false,
'message' => 'Product could not be updated'
], 500);
}
You should take a look at your Product Model to see if name is set as a fillable field: $fillable = ['name'];. Also, the key is probably just name instead of "name".
I want first and last record id form $dataprovider which is passed to gridview which i need to pass to this link.
array(
'name' => 'msg',
'value' => 'CHtml::link(substr(strip_tags($data->msg),0,30)." .....",Yii::app()->createUrl("Mail/view",array("id"=>$data->primaryKey,"flag"=>"inbox","tab"=>'.$tab.',"category"=>'.$category.')))',
'type' => 'raw',
'header' => 'Message',
),
Declare two attributes in your controller.
public $first=null;
public $last=null;
Define a function in controller to render your link
public function renderMailViewLink($data,$row){
// you can return anything you want here. whether a link or whatever
// access $this->first->id , $this->last->id
return CHtml::link($data->anyAttribute,array('someRoute','id'=>$data->id,'first'=>$this->first->id))
}
CActiveDataProvider has a method getData(), which return array of all active records.
in actionIndex
$dataProvider = $model->search()
$data = $dataProvider->getData();
$this->first = reset($data );
$this->last = end($data);
And finally in your view
array(
'name' => 'msg',
'value' => array($this,'renderMailViewLink'),
'type' => 'raw',
'header' => 'Message',
),
Please note this code is not tested. But thats how it can be achieved
I was following along with the Doctrine Hydrator tutorial, but I am having issues saving when my fieldset contains an ObjectSelect. I'm using ORM mapping on my entities. Basically I have a Role entity with id and name. I also have a User entity with id, name and role (ManyToOne). I also have my getters and setters. My setRole() method passes the Role entity as a parameter.
/** #param Role $role */
public function setRole(\Application\Entity\Role $role) {
$this->role = $role;
}
I setup a UserFieldset with a Doctrine Hydrator.
$this->setHydrator(new DoctrineHydrator($objectManager, 'Application\Entity\User'))
->setObject(new User());
The object select for the Role
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'role',
'options' => array(
'label' => 'Role',
'object_manager' => $objectManager,
'target_class' => 'Application\Entity\Role',
'property' => 'name'
)
));
I then setup a UserForm that sets the DoctrineHydrator and adds the UserFieldset.
My controller action
public function addUserAction() {
$objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
$form = new UserForm($objectManager);
$user = new User();
$form->bind($user);
if ($this->request->isPost()) {
$form->setData($this->request->getPost());
if ($form->isValid()) {
$objectManager->persist($user);
$objectManager->flush();
}
}
return array('form' => $form);
}
What seems to be happening is that the ID of the role is passed to setRole rather than an object. As a workaround I've modified my action to:
if ($form->isValid()) {
$objectManager->persist($user);
$data = $this->request->getPost();
$role = $objectManager->find('Application\Entity\Role', $data->user['role']);
$user->setRole($role);
$objectManager->flush();
}
It seems as if this additional step should not be required, but I am not sure if I need to modify my setRole or if I also need to bind a Role entity to the form. This is obviously a simplified example, but my actual forms have many associations that will be tedious to have to code in the controller like this.
UPDATE:
Debug information about post and form.
var_dump($form->getData());
var_dump($this->request->getPost());
Output
object(Application\Entity\User)[395]
protected 'id' => int 6
protected 'name' => string 'Jane Doe' (length=8)
protected 'role' => null
object(Zend\Stdlib\Parameters)[146]
public 'user' =>
array (size=3)
'id' => string '' (length=0)
'name' => string 'Jane Doe' (length=8)
'role' => string '3' (length=1)
public 'submit' => string 'Add User' (length=8)
At long last I got it working. The issue was that I needed to add the role to my input filter on the fieldset
public function getInputFilterSpecification() {
return array(
'name' => array('required' => true),
'role' => array('required' => true)
)
}
... and my validation group on my form.
$this->setValidationGroup(array(
'User' => array(
'name',
'role'
)
));
Now to save the user in my action it is simply
if ($form->isValid()) {
$objectManager->persist($user);
$objectManager->flush();
}
Agent:
agent_id (primary key)
User:
f_id (foreign key)
type
I have created relation in this way
public function relations() {
return array(
'user' => array(self::HAS_ONE, 'Users', 'f_id'),
);
}
But I want to add more conditions like join only if type=3 in User table.
thanks.
There is no error like 'Property "CHasOneRelation.0" is not defined' if you use this:
public function relations()
{
return array(
'user' => array(
self::HAS_ONE,
'Users',
'f_id',
'on' => 'user.ref_type = :type',
'params' => array(':type' => 3))
);
}
See this link: http://www.yiiframework.com/forum/index.php/topic/10185-using-relations-and-conditions/
add the condition on your relation
public function relations() {
return array(
'user' => array(self::HAS_ONE, 'Users', 'f_id', array(
'condition' => 'user.type = :type',
'params' => array(':type'=>3)
)),
);
}
http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-options
You should create a function to get user rather use lazy-load which would use more query even you do not use this relation.
public function getUser(){
return Users::model()->find(array(
'condition'=>'type = :type',
'params' => array(':type'=>3)
));
}
By using this you could use cache function to cache query that relation does not support.
public function getUser(){
return Users::model()->cache(1000)->find(array(
'condition'=>'type = :type',
'params' => array(':type'=>3)
));
}