How to extend a model that is part of an Yii2 extension? - yii2

In my application I'm using an extension (which I own and may modify). This extension has an ActiveRecord based class that I want to extend in the application with another property. Can I do this somehow? Can a Factory help anyhow or Yii behaviour?
Class in extension:
namespace extension;
/**
* #property integer $id
* #property string $name
*/
class Product extends ActiveRecord {
public static function tableName() {
return 'product';
}
/**
* #inheritdoc
*/
public function rules() {
return [
[['id', 'name'], 'required'],
[['id'], 'integer'],
[['name'], 'string'],
];
}
}
There is also a ProductController and the corresponding view files (index, create, update, view, _form) in the extension which were regularly produced with gii. I just would like to add another property $description (string, required) to the Product. A migration in order to add the required column is available.
Do I have to overwrite the model and controller class and the view files? Or is the a more elegant solution?
E.g., consider the standard object creation that takes place within the extension:
public function actionCreate() {
$model = new Product();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'language' => $model->language]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
From my understanding I cannot influence the creation. Or am I wrong?
My impression is that I have to override everything (also the view files since the property has to be displayed) and then change controllerNamespace.

As far as extending a class, just go ahead and add the property. Your new class will have inherited everything from the parent class plus have your new property.
Concerning overwriting the generated files, there is a diff option in gii when you generate the files, so you can preview and decide what to keep and what to overwrite. Be aware that you have to merge any changes manually however.

Related

Yii2 - How to modify controller action param using a behavior?

I'm trying to change the $id param in my controller methods on the fly using beforeAction and a behavior. FYI, I'm going to use HashIds and need to convert anywhere I have a $_GET['id'] that may be hashed back into an integer.
How can I use a behavior to automatically modify my $_GET['id'] on the fly using a behavior?
An example action in my controller:
public function actionView($id){
// run code to process $id here back to integer using a behavior
echo $id; //should be an integer
}
My sample url: http://mydomain/posts/view?id=3QhLp
(Alternatively, perhaps the better way to do this is to create a custom url rule?)
you should implement a class that extends from the \yii\base\Behavior like below
<?php
namespace backend\models;
use Yii;
use yii\base\Behavior;
use yii\web\Controller;
class Transformer extends Behavior
{
public $id = '';
public function events()
{
return [Controller::EVENT_BEFORE_ACTION => 'transform']; //mounting the handler to the 'beforeAction' event on the controller.
}
public function transform()
{
$_GET['id'] = $this->id . "transformed"; //mock method here
return true;
}
}
Then in your controller, adding the code as follow:
public function behaviors()
{
return [
'transformer' => [
'class' => \backend\models\Transformer::className(), //Modify the path to your real behavior class.
'id' => Yii::$app->request->get('id'),
],
];
}
then access the Yii::$app->request->get('id') in your action, you will see the transformed url param.

Having a challenge with Laravel 5.4 requests namespace

I'm trying to reference the Requests class in Laravel, I've tried so many fixes with the keyword "use" but each time I keep getting Reflection exception
that says app\path\specified doesn't exist. I'm confused.
Here is my code:`
<?php
namespace App\Http\Controllers;
//namespace App\Http\Request;
//use Illuminate\Http\Requests;
//use app\Http\Requests\ContactFormRequest;
use App\Message;
use App\Mail\SendMessage;
use Session;
//use App\Requests;
class AboutController extends Controller
{
public function create()
{
return view ('about.contact');
}
public function store(App\Requests\SendMessageRequest $request)
{
$message = $request->message;
Mail::to('myemail')
->send(new SendMessage($message, $request->email,$request->name));
THE REQUESTS CLASS
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SendMessageRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
//
'name' => 'required',
'email' => 'required|email',
"message" => 'required',
];
}
}
The commented line(//) are what I've tried
SendMessageRequest is the name of my Request class.
Sorry, I canĀ“t comment your post. However can you also send the SendMessageRequest Class? Is that a subclass of the Request in Laravel?

Create behavior in yii2

I am using Advanced Template in Yii 2. I want to create behavior for user id, so I made folder in common\components\behavior and created one class,
class UidBehavior extends Behavior
{
public function encryptUid($id)
{
$id = md5($id);
return $this->$id;
}
}
then in user.php =>
'mybehavior' => [
'class' => 'common\components\behavior\UidBehavior',
'encryptUid' => 'id'
],
but error has occurred which is
Setting unknown property: common\components\behavior\UidBehavior::encryptUid
can any one help me ?
You try to init encryptUid property on User.php, Where that is not exist, You can rewrite code like this then all thing work fine:
class UidBehavior extends Behavior
{
public $encryptUid;
public function encryptUid($id)
{
$encryptUid = md5($encryptUid);
return $this->$encryptUid;
}
}
Check Refer Link

Creating a one-to-many relationship in Yii2

Let's say we have two entities: User and Post.
In my understanding, in order to have a one-to-many relationship between User and Post, you need to do the following:
class User {
...
public function getPosts()
{
return $this->hasMany(Order::className(), ['user_id' => 'id']);
}
}
class Post {
...
public function getUser()
{
return $this->hasOne(Order::className(), ['id' => 'user_id']);
}
}
Is this right? Is there anything else I need to add in order to make everything work? The Yii2 documentation is not very clear to me.
Yes, this is enough (except that you inserted Order class name instead), however it's also recommended to add PHPDoc for relations:
User model:
/**
* ...
*
* #property Post[] $posts
*/
class User
{
/**
* #return \yii\db\ActiveQuery
*/
public function getPosts()
{
return $this->hasMany(Post::className(), ['user_id' => 'id']);
}
}
Post model:
/**
* ...
*
* #property User $user
*/
class Post
{
/**
* #return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
}
Then when you will call $user->posts or $post->user you will get full autocomplete if you are using IDE. It's also useful because you can see the relation list just by looking at the top of the file, because relations accessed as virtual properties, $user->getPosts() call will return yii\db\ActiveQuery object and not \yii\db\ActiveRecord array. It's better to separate them with linebreak from model attributes (they are also added for autocomplete and seeing the structure of according database table without looking at database).
By the way, if you generate model with Gii, if you specified foreign keys correctly, relations and PHPDoc will be generated automatically.
Note that if you don't need to use $post->user, you can omit user relation declaration in Post model. You can declare relations that are only needed for usage.

Yii2 - Make Form Validator For URL Type To Skip "http://" in the start

This is how my yii2 model looks like:-
namespace app\models;
use Yii;
use yii\base\Model;
class UrlForm extends Model
{
public $url;
/**
* #return array the validation rules.
*/
public function rules()
{
return [
[['url'], 'required'],
['url', 'url'],
];
}
}
I want it to approve the url if use has not written 'http://' in the start.
Example:-
stackoverflow.com should work fine.
http://stackoverflow.com should work fine.
Current Status:-
stackoverflow.com not accepted.
http://stackoverflow.com is accepted..
You just need to add 'defaultScheme' => 'http' to your validation rule, so
public function rules()
{
return [
[['url'], 'required'],
['url', 'url', 'defaultScheme' => 'http'],
];
}
Test if the parameter URL (most likely as a string) contains http:// at the beginning; if (doesntcontainHTTP){addHttpToURL();}
Example:
class UrlForm extends Model
{
public $url;
/**
* #add "http://" to the url in here
*/
public function rules()
{
/**
* #Place the if statement here
*/
return [
[['url'], 'required'],
['url', 'url'],
];
}
}