How to setup one-to-one relation in yii2 and also other functionalities mentioned below - yii

One User has One Profile(obviously). How do I design the logic behind this?
I have two tables namely "tbl_users" and "tbl_profile".
When I open the profile page, I should be able to see the "Create
Profile" button only if the profile does not exist.
Once the profile has been created by the user, "Create Profile"
button should not appear next time.
Please describe me in detail how the columns of both tables are linked and what changes I have to include in both the models and other changes too.
Thank you.

In your controller you could write something like this:
$user = User::findOne(Yii::$app->user->id);
$profile = $user->profile;
return $this->render('view', ['user' => $user, 'profile' => $profile]);
Then in your view
if(null !== $profile) {
/*show your button here. It's going to work once because...*/
} else {
/*...here you could show form to create your profile*/
}
In your User model use code like this
public function getProfile()
{
return $this->hasOne(Profile::className(), ['id' => 'profile_id']);
}
This is just an example to give you idea.

Related

Restrict data for multiple users

I add multiple users as teacher. And I create a table where every teacher update his data that is documents etc.,but when another teacher login he can also view that data how user to restrict to show that to other users?
You need to read more about Yii, and how you can use it.
For your case you can read this: add condition
For your question you can do this in your action in controller:
0) ensure that user is logged in: \Yii::$app->user->isGuest || //redirect to login page or via Access control filters
1) get user id from user. (\Yii::$app->user->identity->id)
2) set this id in teacher document query. like andWhere(['teacher_id' => $userId]);
public function actionViewDoc()
{ $userId = \Yii::$app->user->identity->id;
$model = TeacherDoc::find()->andWhere(['teacher_id' => $userId]);
return $this->render('viewDoc', [
'model' => $model,
]);
}
This will resolve your issue.
UPD: For more advanced solutions you could use:
1) Access control filters
2) RBAC.

How to use a single form to collect data for two or more models in Yii2?

My problem is to dynamically create forms through jquery.
The user should be able to dynamically generate inputs such that he can save multiple rows into the corresponding model/table in one go.
Now I don't know how do I generate the name attribute for the forms for multiple models. I suppose it should be something like ModelName[Property][] (but I would preferably want to do it in 'Yii way' instead of hardcoding the names)
To understand this better, Here I found a similar post in Yii Wiki.
using a single form to collect data for two or more models
How can this be modified for Yii2? So that the user should be able to fill in data for all the (dynamically generated) rows and submit them in one go.
Tutorial of tabular form for multiple models.
Try this, Reference
public function actionCreate()
{
$user = new User;
$profile = new Profile;
if ($user->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post()) && Model::validateMultiple([$user, $profile])) {
$user->save(false); // skip validation as model is already validated
$profile->user_id = $user->id;
$profile->save(false);
return $this->redirect(['view', 'id' => $user->id]);
} else {
return $this->render('create', [
'user' => $user,
'profile' => $profile,
]);
}
}

Make menu tab on user profile visible only to profile owner

I made a "My bookmarks" tab on the user profile page using Views. The tab shows nodes the user has flagged.
However - "My bookmarks" should only be visible on the user's own profile page and at the moment the "My bookmarks" tab is visible on every profile a user visits. How do I check whether the current user matches the profile being viewed? I tried that from the View interface, but the access permissions don't have any options that work.
EDIT:
I think it is this code, but I still need some guidelines as to how to implement that:
<?php
global $user;
if (arg(0) == 'user' && $user->uid == arg(1)){
return TRUE;
}
else {
return FALSE;
}
?>
I also found this module, I think it helps a lot Views Access Callback
I managed to solve this using the code and module from above.
The custom module contains this code
<?php
function MYMODULE_views_access_callbacks() {
return array(
'MYCALLBACK_user_has_access' => t('User can only see tab on his own profile'));
}
function MYCALLBACK_user_has_access() {
global $user;
if (arg(0) == 'user' && $user->uid == arg(1)){
return TRUE;
}
else {
return FALSE;
}
}
?>
The Views Access Callback module adds your callback to the Views interface and from there, you can use it for your own view.

Allow Administrators to impersonate users using an iframe

I have an MVC project with three roles: Users, Account Managers, and Administrators.
Administrators have their own MVC Area where they have full control over Users and Account Managers. I'm trying to implement functionality to allow Administrators to view the site as any User or Account Manager.
In the Admin Area of the site, I have a View of a list of Users and Account Managers. The list contains a "View Site As User" button for each record.
I have never done anything like this before, but the ViewAs Controller Action is currently set up to create a Session with the selected User's information, like so:
ViewBag.SiteSession = Session["SiteSession"] = new SiteSession()
{
ID = user.ID,
AccountID = user.AccountID,
DisplayName = user.DisplayName,
IsManager = user.IsAdmin,
IsAdmin = false
};
The View relevant to this Action has the Model defined as a string, and nothing else but an iframe with the Model as the src attribute, like so:
#model string
<iframe src="#Model" >
</iframe>
What I'm trying to do is render whichever portion of the site was requested in this iframe. When an Administrator clicks "View As User," I'd like to direct to Home. The URL is generated through this call:
Url.Action("Index", "Home", new { Area = "" }));
The Area is set to nothing to avoid rendering the Admin Area's Home.
Currently, this is not working. I don't know where to even begin, minus what I already have.
I'm looking for any suggestions. All help is greatly appreciated, as this doesn't seem like an easy task.
If you don't know how to help, it would also be appreciated if you could direct this question to somebody that can.
Again, thanks in advance.
The way that I've done this in the past has been to use the concept of an an actual user and an effective user. Most display actions use the effective user to generate their content. Typically I've implemented it as "impersonation" rather than "preview" so the user is actually navigating the site as the user rather than displaying in a separate window. In this case I simply set both in the current session. Things that require admin permission (like switching to/from impersonation) obviously use the real user.
If you wanted to do preview then I'd think about using a parameter on each request to set the effective user. The code would need to understand to add this parameter to all links so that you could navigate in the iframe without messing up navigation in the original interface.
As for removing the area from the url, I think what you have (setting to the empty string) should work. If it's not working you might want to try lowercase area, Url.Action("Index", "Home", new { area = "" }). I'm pretty sure that the RouteValueDictionary that gets created under the hood uses a case insensitive key comparison, though, so it shouldn't matter.
For this task, I ended up creating a separate controller, ViewAsController, which had a controller-wide [Authorize] attribute that only allowed users with the Admin role to access its actions.
In the Start action, a Session object containing the selected User's information is created, like so:
[HttpGet]
public ActionResult Start(int id)
{
var user = db.Users
.First(u => u.ID == id);
Session["SiteSession"] = new SiteSession()
{
//Session data...
};
return PartialView("_IFrame");
}
This Action returns a Partial View that I ended up displaying in a jQuery UI modal dialog window.
Here's the code for that Partial View:
#{
ViewBag.SiteSession = (SiteSession)Session["SiteSession"];
}
<h2>Viewing Site As #ViewBag.SiteSession.DisplayName</h2>
<div>
<iframe src="#Url.Action("Index", "Home", new { Area = "" })"></iframe>
</div>
As you can see, it's extremely bare, and that's exactly what it needs to be. The <iframe> acts as a browser in a browser, allowing the Admin user full access to whichever Actions the selected User would.
For the sake of detail, here's the jQuery that creates the dialog and opens it:
$(function () {
$("#viewAsDialog").dialog({
modal: true,
autoOpen: false,
resizable: true,
draggable: true,
closeOnEscape: false,
height: $(window).height() * .9,
width: 1000,
closeText: '',
close: function () {
$.post("#Url.Action("End", "ViewAs", new { Area = "Admin" })")
.success(function (result) {
});
}
});
});
function viewAs(result) {
$("#viewAsDialog").html(result);
$("#viewAsDialog").dialog("open");
}
You can see here that the dialog is initialized on document-ready, and is not opened until the AJAX call that retrieves the Partial View is successfully completed.
Once the Admin closes the dialog, the server calls the End action in the ViewAs Controller, destroying the session:
[HttpPost]
public ActionResult End()
{
Session["SiteSession"] = null;
return new HttpStatusCodeResult(System.Net.HttpStatusCode.OK);
}

I've to show menu bar with stats like count of messages and updates, also other counts like gifts and messages count

I want to show a menu bar with stats like count of messages and updates, also other counts like gifts, new friend request and messages count.
This menu will be displayed on the all the pages.
How can I write a single method to get all the stats and render partial into the layout and forget about it?
And in other action just concentrate on the main functionality of the page. Without bothering about the menu.
How can I achieve this in Yii?
You're probably looking for a widget. You could for example extend CMenu and do the queries in init() there:
<?php
Yii::import('zii.widgets.CMenu')
class MainMenu extends CMenu
{
public function init()
{
// Do some count queries here. This is just an example,
// your implementation will differ, of course:
$newMessages = Messages::model()->new()->count();
// Now add the menu items:
$this->items = array(
array(
'label' => "$newMessages New messages",
'url' => array('messages/list'),
),
// ...
);
parent::init();
}
}
You then can use this widget in your views/layouts/main.php:
<?php $this->widget('MainMenu'); ?>
You can use beforeAction to achieve this.
As the docs say "This method is invoked right before an action is to be executed (after all possible filters.) You may override this method to do last-minute preparation for the action."
Also you can define public variables in you main controller (Components/Controller.php) so every other controller has access to these. You can then use them in your layout using $this-variable...
Hope this helps :)
You need to create a class that extends CMenu in /protected/components/extendingclassname
<?php
Yii::import('zii.widgets.CMenu');
class Notifications extends CMenu
{
public function init()
{
//query
$requestor=Yii::app()->user->name;
$count = Requests::model()->count( 'requestor=:requestor', array('requestor' => $requestor));
// Now add the menu items:
$this->items = array(
array(
'label' => "$count New messages",
'url' => array('user/notifications'),
),
// ...
);
parent::init();
}
}
?>
Then include the following line within your /layouts.main.php.Hope this helps a beginner who is not sure where to use the class.That's something Michael Härtl forgot to mention.