Is it possible to dynamically change the ModelAdmins $menu_Title to
e.g.
Member::currentUser()->Name ?
How ?
Thanks.
Ok. I got it.
<?php
use SilverStripe\Admin\ModelAdmin;
//...
//...
class UserAdmin extends ModelAdmin
{
private static $managed_models = array(
'YourDataObject'
);
private static $url_segment = 'test';
private static $menu_title = 'Test';
private static $menu_icon_class = 'fa fa-pagelines';
public function getEditForm($id = null, $fields = null)
{
$form = parent::getEditForm($id, $fields);
//.......
//.......
return $form;
}
public static function menu_title($class = null, $localise = true){
//return 'YOUR MENU TITLE';
return Member::currentUser()->Name;
}
}
Related
Every time I close the browser I need to log in again into this app. It is developed in .NET Core 2.0. I'm trying to let it logged in, like every other regular site.
I checked this post that may be useful, but since the code is quite different from this application I decided to create this post.
This is my security code:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
namespace Petito.Common
{
public interface IActivityContext
{
string ActivityID { get; }
IPrincipal User { get; }
}
[JsonObject(MemberSerialization = MemberSerialization.Fields)]
public class ActivityIdentity : IIdentity
{
private string _name = null;
[JsonIgnore()]
private bool _isAuthenticated = false;
[JsonIgnore()]
private string _authenticationType = "";
public ActivityIdentity()
{
}
public ActivityIdentity(string name) : this(name, false, "")
{
}
internal ActivityIdentity(string name, bool isAuthenticated, string authenticationType)
{
this._name = name;
this._isAuthenticated = isAuthenticated;
this._authenticationType = authenticationType;
}
public string Name { get => _name; }
public bool IsAuthenticated { get => _isAuthenticated; }
public string AuthenticationType { get => _authenticationType; }
public static ActivityIdentity Unathenticated => new ActivityIdentity();
}
[JsonObject(MemberSerialization = MemberSerialization.Fields)]
public class ActivityPrincipal : IPrincipal
{
private ActivityIdentity _activityIdentity = null;
private string[] _roles = null;
public ActivityPrincipal() : this(ActivityIdentity.Unathenticated, null)
{
}
public ActivityPrincipal(ActivityIdentity activityIdentity, params string[] roles)
{
_activityIdentity = activityIdentity;
_roles = roles;
}
public ActivityIdentity Identity => _activityIdentity;
IIdentity IPrincipal.Identity => _activityIdentity;
public bool IsInRole(string role)
{
if (_roles != null && _roles.Length > 0)
{
return _roles.Contains(role);
}
return false;
}
}
[JsonObject(MemberSerialization = MemberSerialization.Fields)]
public class ActivityContext : IDisposable, IActivityContext
{
private string _activityID = Guid.NewGuid().ToString();
private DateTime _startDate = DateTime.UtcNow;
private DateTime? _endDate = null;
private ActivityPrincipal _activityPrincipal = null;
public ActivityContext() : this(null)
{
}
public ActivityContext(IPrincipal principal)
{
_activityPrincipal = Convert(principal);
}
private ActivityPrincipal Convert(IPrincipal principal)
{
if (principal == null)
{
return new ActivityPrincipal();
}
var activityPrincipal = principal as ActivityPrincipal;
if (activityPrincipal != null)
{
return activityPrincipal;
}
var claimsPrincipal = principal as ClaimsPrincipal;
if (claimsPrincipal != null)
{
var roles = claimsPrincipal.Claims.Select(x => x.Value);
var p = new ActivityPrincipal(
new ActivityIdentity(claimsPrincipal.Identity.Name, claimsPrincipal.Identity.IsAuthenticated, claimsPrincipal.Identity.AuthenticationType)
, roles.ToArray()
);
return p;
}
throw new NotSupportedException($"Converting {principal.GetType()} not supported");
}
public void Dispose()
{
if (!_endDate.HasValue)
{
_endDate = DateTime.UtcNow;
}
}
public string ActivityID { get => _activityID; }
public DateTime StartDate { get => _startDate; }
public DateTime? EndDate { get => _endDate; }
public IPrincipal User
{
get
{
return _activityPrincipal;
}
}
}
}
Of course, I'll still try to figure out what's wrong with the code. Please if you need another part of the code other from that I posted let me know.
Thanks!
I have this class to connect to my database, but when I try to use it, always return null.
if I use these credentials in a single php file without class and static function, it works.
This is how I use it
<?php
include 'bdconexion.php';
$var ="hola";
$pdo=BaseDatos::Conectar();
print '<h3>PDO: simple select</h3>';
foreach($pdo->query( 'SELECT * FROM productos;' ) as $row)
{
echo $row['descripcion'];
}
Some help will be great
class BaseDatos
{
private static $bdname = 'bd';
private static $bdhost = 'localhost';
private static $user = 'root';
private static $pass = 'pass';
//private static $mssqldriver = '{SQL Server}';
//private static $mssqldriver = '{SQL Server Native Client 11.0}';
//private static $mssqldriver = '{ODBC Driver 11 for SQL Server}';
private static $conn = null;
public function __construct()
{
die('La funcion de inicio no es permitida');
}
public static function conectar()
{
if (null==self::$conn) {
try {
$conn = new PDO("mysql:host=".self::$bdhost.";dbname=".self::$bdname,self::$user,self::$pass);
} catch (PDOException $e) {
die($e->getMessage());
}
}
return self::$conn;
}
public static function desconectar()
{
self::$conn=null;
}
}
How validate parameters in yii2?
I try, but not work validate:
I want validate in BaseData parameters - $key_active = '0', $login = '0'
class MyController extends Controller
{
public function actionMy($key_active = '0', $login = '0')
{
$model = new Mymodel();
if($model->validate()){
return $this->render('yes');
}
return $this->render('no');
}
}
class Mymodel extends Model
{
public $login;
public function rules()
{
return [
[['login'], 'unique', 'targetClass' => '\app\models\Account', 'message'=>'Этот email уже существует.'],
];
}
}
Maybe it's the wrong thing to be validated?
If you want to validate custom data, you need to add custom properties to model and add it rules.
public function actionMy($key_active = '0', $login = '0')
{
$model = new Mymodel();
$model->key_active = $key_active;
$modle->login = $login;
if($model->validate()){
return $this->render('yes');
}
return $this->render('no');
}
then in model
class Mymodel extends Model
{
public $login;
public $key_active;
public function rules()
{
return [
['login', 'unique', 'targetClass' => '\app\models\Account', 'message'=>'Этот email уже существует.'],
['key_active', 'YOUR_VALIDATION_RULES_HERE'],
];
}
}
$model = new Mymodel();
$model->key_active = $key_active;
$model->login = $login;
I used code
$sql="SELECT 'Name' FROM XXX";
$names =$connection->createCommand($sql)->query()->readAll();
$myDynamicObject = new DynamicModel($names);
class DynamicModel extends CModel
{
protected $_members = array();
public function __construct($nameFields)
{
foreach ($nameFields as $member) {
$this->_members[$member] = null;
}
parent::__construct();
}
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
$allMembers = implode(', ', array_keys($this->_members));
return array(
array($allMembers, 'required'),
);
}
public function __get($attribute)
{
if (in_array($attribute, array_keys($this->_members))) {
return $this->_members[$attribute];
} else {
return parent::__get($attribute);
}
}
public function __set($attribute, $value)
{
if (in_array($attribute, array_keys($this->_members))) {
return $this->_members[$attribute] = $value;
} else {
return parent::__set($attribute, $value);
}
}
public function getAttributes()
{
return $this->_members;
}
public function setAttributes($attributes)
{
$this->_members = $attributes;
}
}
i print this model in controller but
not nothing coming..server error came..
" More
An unexpected condition was encountered while the server was attempting to fulfill the request.
Error code: 500"
CModel is an abstract class and you need to at least implement the attributeNames() function.
In your case I guess the following should suffice:
public function attributeNames()
{
return array_keys($this->_members);
}
This question already has answers here:
Call to a member function on a non-object [duplicate]
(8 answers)
Closed 10 years ago.
I'm trying to make oop class to get user info but i get this error
Fatal error: Call to a member function prepare() on a non-object in functions.php
user.php - >
include_once 'functions.php';
$user = new User();
echo $user->get_fullname(5);
functions.php ->
include_once 'database.php';
class User
{
public function connect()
{
$dbh = new DB_Class();
}
public function get_fullname($uid)
{
$getName = $dbh->prepare("SELECT EmailAddress FROM users WHERE UserID =:username");
$getName->bindParam(':username', $uid);
$getName->execute();
$rowName = $getName->fetch();
$email = $rowName['emailaddress'];
return $email;
}
}
database.php - >
class DB_Class
{
public function connect() {
try {
$dbh= new PDO("mysql:host=localhost;dbname=root",'users','password', array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
));
} catch (PDOException $e) {
echo $e->getMessage();
}
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
$dbh->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER);
}
}
What i'm doing wrong :(
You never actually give access to the PDO instance $dbh to the things youre trying to use it in. It seems like youre using classes simple as groupings of functions but also expecting some magic to happen :-) This is how i would do it with your existingcode:
class DB_Class {
protected $dsn;
protected $user;
protected $password;
protected $connection;
public function __construct($dsn = null, $user = null, $password = null)
{
$this->dsn = $dsn;
$this->user = $user;
$this->password = $password;
}
public function connect()
{
if($this->connection) {
return $this->connection;
}
try {
$this->connection = new PDO($this->dsn,$this->user, $this->password,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
));
$this->connection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
$this->connection->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER);
return $this->connection;
}
catch (PDOException $e) {
return false;
}
}
}
class User {
protected $db;
public function __construct(DB_Class $db = null)
{
$this->db = $db;
}
public function setDb(DB_Class $db)
{
$this->db = $db;
}
public function get_fullname($uid)
{
$stmt = $this->db->connect()->prepare("SELECT EmailAddress FROM users WHERE UserID =:username");
$stmt->execute(array(':username', $uid));
if($row = $getName->fetch()) {
return $row['emailaddress'];
} else {
return null;
}
}
}
The $dbh variable isn't being passed into the get_fullname function. You'd need to do something like:
public function connect()
{
$dbh = new DB_Class();
return $dbh;
}
public function get_fullname($uid)
{
$dbh = $this->connect();
you need to declare $dbh as property of User class and access it via $this identifier:
class User
{
protected $dbh;
public function connect()
{
$this->dbh = new DB_Class();
}
public function get_fullname($uid)
{
$getName =$this->dbh->prepare("SELECT EmailAddress FROM users WHERE UserID =:username");
$getName->bindParam(':username', $uid);
$getName->execute();
$rowName = $getName->fetch();
$email = $rowMail['emailaddress'];
return $email;
}
}
You are never actually assigning your class properties as a property, all you are doing when declaring the variables inside of your methods is putting them into the methods current scope and they are destroyed once the method finishes execution.
To properly set a property within a class you need to declare them using $this->varname and the same goes for accessing them.
You are also using an incorrect name for the classes construction, the constructor must be set to __construct not connect.
As you can see in the updated code the $dbh variable is now a property of the User class and can be called between it's methods.
User Class
class User
{
public function __construct()
{
$this->dbh = new DB_Class();
}
public function get_fullname($uid)
{
$getName = $this->dbh->getConnection()->prepare("SELECT EmailAddress FROM users WHERE UserID =:username");
$getName->bindParam(':username', $uid);
$getName->execute();
$rowName = $getName->fetch();
$email = $rowName['emailaddress'];
return $email;
}
}
Database Class
class DB_Class
{
public function __construct() {
try {
$this->dbh = new PDO("mysql:host=localhost;dbname=root",'users','password', array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
));
} catch (PDOException $e) {
echo $e->getMessage();
}
$this->dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
$this->dbh->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER);
}
public function getConnection() {
return $this->dbh;
}
}
You will benefit greatly by using http://us2.php.net/manual/en/oop5.intro.php as a resource.