How to implement for approval model on laravel nova - laravel-nova

I have resource Post and after create or update, this post data moving in approval model.
And the approval have status: reject, revision and approved.
how to implement in approval model, because i have tired. thanks

Your resources use Model Events because Nova is using Eloquent.
So assuming you're managing a status with a select:
<?php
namespace App\Nova;
use Laravel\Nova\Fields\Select;
class Post
{
public function fields()
{
return [
...
Select::make('Status')->options([
'approved' => 'Approved',
'rejected' => 'Rejected',
'revising' => 'Revising',
]);
];
}
}
You would then listen to a post's status upon saving by listening for that event:
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Post::observe(PostObserver::class);
}
}
<?php
namespace App\Observers;
class PostObserver
{
public function saving($post)
{
if($post->status == 'approved') {
//
}
}
}
It is worth noting, saving() catches the post before it is saved()
You can hook onto these statuses within the Observer and perform more behavior.
So if you wanted to create an additional model when status changes:
<?php
namespace App\Observers;
class PostObserver
{
public function saving($post)
{
if($post->isDirty('status'))
{
Approval::create([
'post_id' => $post->id,
'user_id' => auth()->id(),
'status' => $post->status,
]);
}
}
}
Or any task related to the status change, for example sending mail:
<?php
namespace App\Observers;
class PostObserver
{
public function saving($post)
{
if($post->isDirty('status') && $post->status == 'rejected')
{
Mail::to($post->author)->send(new PostRejected($post));
}
}
}
Although, if you have an Approval model.. I'd say put that in the ApprovalObserver in created
~ Brian Dillingham (#im_brian_d)

Related

Error 403: Insufficient Scope returned while using Google People Api for accessing user contacts

I am using yii2-authclient to authorize users and import google contact list
Steps I followed:
Created Project in Google Console and enabled People API
Setup config parameters, controllers, etc using docs. Tested Login and it worked fine. Configured it for contact redirect URI too.
For Contacts, created a child class of \yii\authclient\clients\Google and made several tweaks:
class Google extends \yii\authclient\clients\Google {
/**
* #var array list of attribute names, which should be requested from API to initialize contact list.
*/
public $attributeNames = [
'names',
'emailAddresses',
];
/**
* Set base URL according for Contacts API
*/
public function init() {
parent::init();
$this->apiBaseUrl = 'https://people.googleapis.com/v1';
if ($this->scope === null) {
$this->scope = implode(' ', [
'https://www.googleapis.com/auth/contacts',
'https://www.googleapis.com/auth/contacts.readonly',
]);
}
}
/**
* Call people.connection.list end point
*/
protected function initUserAttributes() {
return $this->api('people/me/connections', 'GET', [
'personFields' => implode(',', $this->attributeNames),
'pageSize' => 2000,
]);
}
}
Inside a controller:
public function actions() {
return [
'import' => [
'class' => 'yii\authclient\AuthAction',
'clientIdGetParamName' => 'authclient',
'clientCollection' => '[collection_name_from_config]',
'successCallback' => [$this, 'onImportSuccess'],
],
];
}
public function onImportSuccess($client) {
...
$contacts = $client->getUserAttributes();
...
}
You might need to add the scope for basic profile information: https://www.googleapis.com/auth/userinfo.profile.
Scope list: https://developers.google.com/identity/protocols/googlescopes#peoplev1

Yii2 createurl with integer parameter

I got the error
syntax error, unexpected '‌' (T_STRING)
that's my link
<?php $url=Yii::$app->getUrlManager()->createUrl('admin/message/chat',array('idUser'=>$contact['id'])‌);?>
and inside the rules function i add the following link:
[['admin/message/chat/idUser/' => 'admin/message/chat']],
and my action's script looks like:
public function actionChat($idUser = null)
{
$searchModel = new MessageSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'$idUser' => $idUser,
]);
}
Your error is in
'$idUser' => $idUser,
It should be
'idUser' => $idUser,
Could be you missed some closing } eg: at the end of an action or at the end of the controller class
class MessageController extends Controller
{
public function actionChat()
{
......
}
} // check for this

How to use dynamic Type Hints in Laravel method

Basically I want to make code generic and use different Services upon given Route parameters.
What is the proper and working way to achieve this?
The following works:
Routes:
Route::get('socialmediaAccount/authorize/twitter', function(TwitterApi $client){ return ['Works'];});
That works as well:
Routes
Route::get('socialmediaAccount/authorize/twitter', ['uses' => 'SocialmediaController#authorizeAccount']);
Controller
class SocialmediaController extends Controller
{
public function authorizeAccount(TwitterApi $client)
{
return ['Works as well'];
}
}
Now I want to add facebook, the idea is this:
Routes
Route::get('socialmediaAccount/authorize/{type}', ['uses' => 'SocialmediaController#authorizeAccount']);
Controller
class SocialmediaController extends Controller
{
public function authorizeAccount($type)
{
if($type == 'twitter') {
$client->call TwitterApi-method(); //????????????
return ['???'];
}
if($type == 'facebook') {
$client->call FacebookApi-method(); //????????????
return ['???'];
}
}
}
Since this didn't work I tried and failed with following:
Now in the definition of my Controller method I can't use the Type Hint anymore, and if I try to create separate methods ala authorizeTwitter I can't call it with Type Hint. I tried following:
Routes - is the same
Controller
class SocialmediaController extends Controller
{
public function authorizeAccount($type)
{
if($type == 'twitter') {
$this->authorizeTwitter();
return ['???'];
}
if($type == 'facebook') {
$this->authorizeFacebook();
return ['???'];
}
}
private function authorizeTwitter(TwitterApi $client) //????????????
{
call TwitterApi-method();
}
private function authorizeFacebook(FacebookApi $client) //????????????
{
call TwitterApi-method();
}
}
The error here is 'Argument 1 passed to ... must be an instance of ... TwitterApi, none given.
You can't use dependency injection on methods that you call manually. Only on route methods, because route methods will be resolved automatically.
This said the following should work:
class SocialmediaController extends Controller
{
public function authorizeAccount($type, TwitterApi $twitterClient, FacebookApi $facebookClient)
{
if($type == 'twitter') {
// do Twitter authorization using $twitterClient here
}
if($type == 'facebook') {
// do Facebook authorization using $facebookClient here
}
}
}

NHibernate and HasMany mapping

i have trivial mapping for two entities: poll and polloption
Poll:
public class PollMap : ClassMap<Poll>
{
public PollMap() {
Id(x => x.Id);
Map(x => x.Content);
HasMany(x => x.PollOptions).Cascade.All();
}
}
PollOption:
public class PollOptionMap : ClassMap<PollOption>
{
public PollOptionMap() {
Id(x => x.Id);
Map(x => x.Content);
References(x => x.Poll);
}
}
in test code im trying to remove the first polloption of poll entity
Test code:
[Transaction]
public ActionResult Add() {
var poll = new Poll() {
Content = "poll",
PollOptions = new List<PollOption>() {
new PollOption(){
Content="PollOption#1"
},
new PollOption(){
Content="PollOption#2"
}
}
};
GetSession.Save(poll);
return Content("Added");
}
[Transaction]
public ActionResult Removed() {
var poll = GetSession.Query<Poll>().FirstOrDefault();
poll.PollOptions.RemoveAt(0);
GetSession.Update(poll);
return Content("Updated");
}
when the remove action fired it not deleting polloption from db instead it set null in my foreign key :(
ps. google not helped
Cascade.All() only deletes the child object if the parent is deleted. If you want the childs to get deleted when they are removed from the collection, you need Cascade.AllDeleteOrphan().
Additional note: You also have to mark one side of your bidirectional association as Inverse(). More info about that here: http://nhibernate.info/doc/nh/en/index.html#collections-bidirectional

Taking advantage of Doctrine relations in frontend applications in Symfony

Let's consider the following simple schema (in Doctrine, but Propel users are welcome too):
User:
columns:
name: string
Article:
columns:
user_id: integer
content: string
relations:
User:
local: user_id
foreign: id
Now, if you create a route for Article model and generate a module via doctrine:generate-module-for-route frontend #article_route you get a CRUD application that manages all the articles. But in frontend you would normally want to manage objects related to signed-in User, so you have to manually get the id of the User, pass id to the model and write a bunch of methods that would retrieve objects related to this User, for example:
public function executeIndex(sfWebRequest $request)
{
$this->articles = Doctrine::getTable('Articles')
->getUserArticles(this->getUser());
}
public function executeShow(sfWebRequest $request)
{
$this->article = $this->getRoute()->getObject();
if (!$this->article->belongsToUser($this->getUser()))
{
$this->redirect404();
}
}
and model:
class ArticleTable extends Doctrine_Table
{
public function getUserArticles(sfUser $user)
{
$q = $this->createQuery('a')
->where('a.user_id = ?', $user->getId());
return $q->execute();
}
}
class Article extends BaseArticle
{
public function belongsToUser(sfUser $user)
{
return $this->getUserId() == $user->getId();
}
}
This is trivial stuff and yet you have to manually write this code for each new relation. Am I missing some kind of way to take advantage of Doctrine relations? Anyways, how would you do it? Thank you.
I believe you should be able to do this with a custom routing class. I have never done this, but there is a tutorial in the More with Symfony book: Advanced Routing. My guess is that it should look something like this:
class objectWithUserRoute extends sfDoctrineRoute
{
public function matchesUrl($url, $context = array())
{
if (false === $parameters = parent::matchesUrl($url, $context))
{
return false;
}
$parameters['user_id'] = sfContext::getInstance()->getUser()->getId();
return array_merge(array('user_id' => sfContext::getInstance()->getUser()->getId()), $parameters);
}
protected function getRealVariables()
{
return array_merge(array('user_id'), parent::getRealVariables());
}
protected function doConvertObjectToArray($object)
{
$parameters = parent::doConvertObjectToArray($object);
unset($parameters['user_id']);
return $parameters;
}
}
You would then need to set the routing class in routing.yml to use objectWithUserRoute. I haven't tested this, but I think it is the best way to go about solving the problem.

Resources