adding a user id step in actionCreate() - yii

I'm new to Yii. I have a table where I'd like to add a user ID at the time of creation of an entry. I've identified actionCreate() in the associated Controller, which I guess is the appropriate place to make my ammendment. The only thing is I can't find any documentation on what I should now do. Can I ask for help on what I should no next.
thanks

You're probably looking for afterSave(). You can add a method like this to your User model:
protected function afterSave()
{
if($this->isNewRecord) {
// Insert ID into other table here
}
}

Simply set the field to primary and autoincrement in the database. This value will automatically be added after calling ->save() on the new object.
You will be able to access this ID field with $model->primaryKey

Related

How to use a Model object across a number of Controllers?

SCENARIO: After the user has successfully logged in, I want to create an Account object (Account class is a part of my model) and fetch and store the user's information in it. I want this Account object to be accessible to all my controllers (HomeController, AccountController etc) and also, I want the ability to edit its content from inside any controller. (1) How can I achieve this scenario? (2) How can I pass a model object from one controller to another?
I intend to keep it till the user logs out
Then you can use session. But I suggest not saving a lot of information. So for example you have this model or entity:
public class AccountModel {
public int Id {get;set;}
public string Username {get;set;}
// and a whole lot more of properties
}
I suggest you just store an identifier field, either the Id or the Username. Then when another request comes in and you need to either validate the request or update that same model, you can:
Fetch the data again for that user and all relevant information
Update the necessary fields
Save it in your database
So you would do something like:
// to save it in a session after logging in
Session["current_user_id"] = id_variable;
// to retrieve it from session after another request comes in
var id = (int)Session["current_user_id"];
// fetch from your database
// do the necessary update
// persist the changes
(1) How can I achieve this scenario?
You could retrieve the Account model from your datastore when you need to access it.
(2) How can I pass a model object from one controller to another?
See (1). Since you are retrieving it from the data store you don't need to be passing it around.

MVC 4 Lookup UserName Based on UserId

I'm using the MVC 4 template with VS 2012. I have enabled a comments section which stores the logged in user's UserId to a table. When I display the comments I want to display the user's user name and email from the UserProfiles table.
I've tried the following code:
public static string GetUserName(int userId)
{
using (var db = new UsersContext())
{
return db.UserProfiles.Single(x => x.UserId == userId).UserName;
}
}
But I get an exception:
The model backing the 'UsersContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
Any suggestions?
The exception is pretty descriptive. Your model does not reflect what your database look like. I recommend you to read this about code first migrations, basically what migrations mean is that you update your database to match your models, its done with one line of command in VS.
Hope this helps
Also I would recommend you to use .Find() or .First() instead of .Single()

Adding more info to Laravel's auth user

I am new to Laravel and I am trying to add some more information to the user variable I am getting back from Auth::user()
To be more detailed, I have a Many-to-Many relationship to a "Privileges" table. As the name suggests, that table holds specific privileges a user can have. In the pivot table, I just hold the the user_id and privilege_id. I have the necessary models set up and everything works fine if I do this in my before filter:
$user = Auth::user();
$user->priviledges()->get();
Now, I would really like to avoid querying every single time I want to find the privileges and would like to have Laravel's Auth class include the privilege information, so that when I do
$user = Auth::user();
I can do a
$user->privileges;
to get an array of all privileges the user has.
Any suggestions for the best approach?
The link to the answer above is not working. However, I found another solution here which worked for me as follows:
First I created a model called EmailPref.php in my own case;
app/model/EmailPref.php
class EmailPref extends Eloquent {
protected $table = 'email_pref';
public function user()
{
return $this->belongsTo('User');
}
}
and then I created a relationship (in my own case) in the User model like so;
app/model/User.php
public function emailPref()
{
return $this->hasOne('EmailPref');
}
I subsequently referenced it anywhere required within my application like so:
Auth::user()->emailPref;
Hence, I was able to add more information to the Auth user.
I'm no Laravel pro, but i think this will solve your problem: http://forums.laravel.io/viewtopic.php?id=1652

SPListItem id from SPField object

I am working on create a custom field type and for implementation issue I need to retrieve the ID of the SPListItem in the SPField class which belong to these field type but I can't retrieve it.
For example:
public class myField:SPFieldText
{
// I need ListItemID in this class
}
Can anyone help me please?
SPFieldText is an SPField, which is the schema definition for a field. Its like saying, given an SQL create table statement, give me the id of row x. Can't be done.
I think the logic you are trying to perform should be done in an event receiver, so say when an item is saved, you take the ID and add it to the text field.
I didn't find a solution but I've tried another solution which is
I can get the ID of the item in the New and Edit forms so I saved the ID and the field value as a one value separated by '/' and in the SPFieldText class I've been able to retrieve the ID value from the value of the field

Why does NHibernate need to know the ID of an auto ID based entity before flush is called?

With my only ORM knowledge being L2S/EF, I was surprised when the following code inserted a row into the database before I called repo.Save:
var repo = new UserRepository();
var user = new User { Name = "test" }
repo.Add(user);
//repo.Save();
Repo looks like this:
public void Add(T entity)
{
session.Save(entity);
}
public void Save()
{
session.Flush();
}
After some digging, it seems NHibernate needs to make the insert happen right away in order to get the ID of the new entity (since it's using an auto increment ID). But L2S/EF doesn't work like this; I can add many entities and save them all at the end.
Question is: is there a way to achieve the same thing with NHibernate, while still using auto increment IDs, and out of interest does anyone know why it works like this?
Fabio Maulo already blogged about the usage of identity generator a few times. The answer is: use hilo, guid.comb or something like this.
NHibernate needs the identity because every entity in the session (they are called "persistent entities") needs to be identified. The identity is also normally used to determine if the record already exists in the database (unsaved value).
session.Save actually only makes a transient entity persistent. When the database is generating the id, it needs to be stored to get the id. If NH can create the id itself (eg using hilo), it could be stored next time when the session gets flushed.