Yii2: Display GET params in url on the index page using ActiveDataProvider - yii2

I use ActiveDataProvider and Gridview in my site. Get parameters appear in url only after searching for some field (they are missing on the index page when the site first loads).
How can I by default add some GET parameters in url when first loading the index page has not yet been searched.

If your action is called "mySearch", here an example to use a default value if parameters is missing:
public function actionMySearch()
{
// Flat php
$mySearchName = isset($_GET['MySearch']['name']) ? $_GET['MySearch']['name'] :'John';
$mySearchEmail = isset($_GET['MySearch']['email']) ? $_GET['MySearch']['email'] : 'john#test.com';
// Yii helpers
$mySearchName = \yii\helpers\ArrayHelper::getValue($_GET, 'MySearch.name', 'John');
$mySearchEmail = \yii\helpers\ArrayHelper::getValue($_GET, 'MySearch.email', 'john#test.com');
}

Related

How to return a default column value for mass assignment of a model?

I am using mass assignment to create a server model like so:
/** #var Model $server */
$server = Server::create($request->all());
return response($server->jsonSerialize(), Response::HTTP_CREATED);
Now my server also has a status property which maps to a MySQL status column which has a default value of 0 in MySQL.
Because the status is not being set implicitly in my request attributes(no need since the default is fine) it does not return the status property on the model. It will return all of the properties in my $request->all() though. These are validated and coming from a form.
How can I return my full $server model including the default value for status? I am forced to fire off another query to re-fetch the model I have just created, just so I can also include the status property with the MySQL default?
It doesn't do a selecet after an insert so you wont get any values that the DB has to set itself. You can refresh the model instance though (cause it to select that row):
$model->refresh();
If you're returning it as JSON, you can add status to protected $appends = ["status"];
class Server extends Model {
protected $appends = ["status"];
...
}
That way, even if you don't set status in your Server::create() method, it should still be visible in your JSON response as server.status. Also, perhaps adjust your return to
return response()->json(["server" => $server], 200); // or whatever HTTP code you need.
Since $appends only works with accessors, perhaps use $request->merge() to "fill in the gaps" for data you want returned in your JSON response:
$request->merge([
"status" => "active", // Or whatever the default is from the database
...
]);
Since the response is returning everything in $request->all(), merge it with default values from MySQL. Note: currently hardcoded, would need to be updated if migration/schema changed, or via SQL command to get defaults.

How to use Url::remember in yii2

I want to create a link on my error page to take user back to the previous link.
Suppose the current URL is http://example.com/site/product, and a user try to view
http://example.com/site/product?id=100 and a product with id =100 does not exit, the system should throw 404 error to the error page, now if i want to create a link to take the user back to http://example.com/site/product the previous URl how do I make this work. i can make this work by hardcoding this in my error views file, but i want it dynamically as i have many controller an action using the same view file.
I try this in my site conteoller
controller/site
public function actions()
{
$url = Url::remember();
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
$this->render('error',['url'=>$url]),
];
}
and try to get the value the in error view file like this
/views/site/error.php
<p>
<?= Html::a('go back', [$url)?>
</p>
but it has no vaule..
please any good idea on how to make this work, am also open to new solution
this is form Yii2 Guide http://www.yiiframework.com/doc-2.0/guide-helper-url.html#remember-urls
There are cases when you need to remember URL and afterwards use it
during processing of the one of sequential requests. It can be
achieved in the following way:
// Remember current URL Url::remember();
// Remember URL specified. See Url::to() for argument format.
Url::remember(['product/view', 'id' => 42]);
// Remember URL specified with a name given
Url::remember(['product/view', 'id' => 42], 'product');
In the next
request we can get URL remembered in the following way:
$url = Url::previous();
// or
$productUrl = Url::previous('product');

How to use article name on the url on Yii2?

I need to use article name on the url on Yii2 which is like http://example.com/article?id=1, just replace id=1 to article_name, like http://example.com/article/article_name or is it.
This is my controller code-
$model = Articles::find()->orderBy(['id' => SORT_DESC])->one();
View-
<?= Html::a('<b>Read more ...</b>', ['article-details','id' => $model->id], ['target'=>'_blank']) ?>
Thanks advance
You may use yii2 sluggable behavior Refer this.
There are few steps.
You must add the following urlManager rule :
'article/<slug>' => 'article/view',
You should build url in your view files like this :
\yii\helpers\Url::to(['article/view', 'slug'=>$model->title])
or
\yii\helpers\Url::to(['article/'.$model->title]);
And in your action
public function actionArticle($slug){
$model = Articles::find()->where(["title"=>$slug])->orderBy(['id' => SORT_DESC])->one();
//and other code
}
Also your article titles must be valid for url.You can do it easly by trimming whitespaces and so on But also you can add url some identification propery. or add column stored unique slugs for every article
You have two way
one change the related action in the controller changing id with name in the related function declaration
or declare a new action with the name as parameter
public function findModelName($article_name)
{
$model = Article::findOne(['name'=> $article_name]);
........ your related code
}
you can find the model by name this way
Article::findOne(['name'=> $article_name]);

Foreign keys and uploading a photo in yii 1.1

i did these two tasks separately but now i am not being able to use both of these tasks at a single place.
Problem statement:
I have a table name Business_items having foreign keys of table business and items. In model class here is the relation function.
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'business' => array(self::BELONGS_TO, 'Business', 'business_id'),
'items' => array(self::BELONGS_TO, 'Items', 'items_id'),
'itemReviews' => array(self::HAS_MANY, 'ItemReview', 'business_items_id'),
);
}
ok, in create business page, i have two fields, business name, items name and a third thing which is upload image. Both of the fields are searchable drop downs. I am taking business name and items name with the help of foreign keys. so i can see the values inside my business_items which were used to be keys. i did this by changing this code.
public function actionCreate()
{
$model=new PackageItems;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['PackageItems']))
{
$temp=$model->items_id=$_POST['PackageItems']['items_id']; //items_id is a multiple list field
foreach($temp as $t)
{
$model->unsetAttributes();
$model->setIsNewRecord(true);
$model->package_id=$_POST['PackageItems']['package_id']; //package_id is a repeated field
$model->items_id=$t;
$model->insert();
}
if($model->save())
$this->redirect(array('admin','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
so what i wanted i actually accomplished which was
id----items----package
1------cake-----buy one get one free
2----- pastry-----buy one get one free
second part:
I know how to upload image in yii, i followed this link and it worked http://www.yiiframework.com/wiki/349/how-to-upload-image-photo-and-path-entry-in-database-with-update-functionality/
separately now the problem is i want something like that
id----items----package-----------------------image
1------cake-----buy one get one free------1.jpg
2----- pastry-----buy one get one free------1.jpg
but the problem is
public function actionCreate()
{
$model=new Banner; // this is my model related to table
if(isset($_POST['Banner']))
{
$rnd = rand(0,9999); // generate random number between 0-9999
$model->attributes=$_POST['Banner'];
$uploadedFile=CUploadedFile::getInstance($model,'image');
$fileName = "{$rnd}-{$uploadedFile}"; // random number + file name
$model->image = $fileName;
if($model->save())
{
$uploadedFile->saveAs(Yii::app()->basePath.'/../banner/'.$fileName); // image will uplode to rootDirectory/banner/
$this->redirect(array('admin'));
}
}
$this->render('create',array(
'model'=>$model,
));
}
how can i use both of these codes (getting value using foreign key code and picture uploading code) i want to upload pictures as well as get the value from some other table using foreign key with my code.
I know its complicated but i need help.
Thanks and sorry in advance.
I'm not sure if I get your problem right, but as far as I understood, you want to upload a file and insert the name of this file in one of your database tables. If that's the case, a solution could be as follows:
First, add a new field to your database table in which you will store the file name, also add it to your ActiveRecord class and to your view.
Then add your code to save your related records (I think your foreach loop is for that).
Next add a the necessary code to upload the image. In the code to upload the image you can see that Yii will treat the file field like a normal text field, in which you will store the uploaded file name.
Finally you should save your model and, if it succeded, then proceed to save the file in the server.
Hope this helps.
UPDATE
I'll put some code in order to clarify my answer.
You say that the first part works for you, then I'll begin with that.
Your model PackageItems needs a new field, let it be image.
Next, I'm assuming that the user filled the form, so I'll skip the if and the render parts
$temp=$model->items_id=$_POST['PackageItems']['items_id'];
$uploadedFile=CUploadedFile::getInstance($model,'image');//get uploaded image info
$rnd = rand(0,9999);
$fileName = "{$rnd}-{$uploadedFile}"; // random number + file name
$model->image = $fileName;//store the new file name in the model
foreach($temp as $t){
$model->unsetAttributes();
$model->setIsNewRecord(true);
$model->package_id=$_POST['PackageItems']['package_id'];
$model->items_id=$t;
$model->insert();
}
if($model->save()){
$uploadedFile->saveAs(Yii::app()->basePath.'/../yourPath/'.$fileName);//if the record was saved in the database, then proceed to save the image in the server
$this->redirect(array('admin','id'=>$model->id));
}
If you want to upload multiple files check this link Yii 1.1: Uploading multiple images with CMultiFileUpload

YII2 : Use activeForm and linkPager toghether

I would like to use an activeForm and linkPager together.
I mean in the same view, I have defined an activeform with some fields, an sqldataprovider and the showing of the model result (of sqldataprovider). All is nice when I click on the submit button of the activeform.
Now, I would like to add a linkPager by using :
echo \yii\widgets\LinkPager::widget([
'pagination'=>$dataProvider->pagination,
]);
And when I click and one of buttons of linkpager (to change page), the fields of the activeform are not linked, I mean : the datasqlprovider does not filter with these fields...
I think, you need to populate the ActiveForm manually based on the request parameter:
$searchModel = new JobSeekerSearch(); // extended from JobSeeker
$params = Yii::$app->request->queryParams; // this is the query string parameter
if( !empty( $params['JobSeekerSearch'] ) ){
$searchModel->fullName = $params['JobSeekerSearch']['fullName']; // populate your model
}
$dataProvider = $searchModel->search($params); // submit the search parameter to your search model
then make sure to create your ActiveForm based on the model(JobSeekerSearch for this example)