I want to factory seed a translatable model without hardcoding the locales.
There are two values that I have to seed, slug which is not translatable, and
title which has to be translated to all the languages from the languages table.
Here is the factory file:
$factory->define(App\Category::class, function (Faker $faker) {
$counter = 1;
$locales = Language::pluck('lang'); //returns hr,en,de
$titles = [];
foreach ($locales as $locale) {
$titles[$locale] = [
'title' => 'Title for category-' .$counter++. ' on '. $locale . ' language'
];
}
/*
$titles =
"hr" => array:1 [
"title" => "Title for category-1 on hr language"
]
"en" => array:1 [
"title" => "Title for category-2 on en language"
...
*/
return [
'slug' => 'category-'.$counter++,
$titles
];
});
This gives me an error:
Column not found: 1054 Unknown column 'hr'
Query created by the factory:
insert in
to category_translations (locale, hr, en, de, test, category_id) values (0, Title for category-1 on hr language, Title
for category-2 on en language, Title for category-3 on de languag
e, Title for category-4 on test language, 20))
Solution for Laravel 9
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* #extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Attribute>
*/
class AttributeFactory extends Factory
{
/**
* Define the model's default state.
*
* #return array<string, mixed>
*/
public function definition()
{
$title = faker_translation('lastName');
return [
'title' => $title,
];
}
}
app.php
'fallback_locale' => 'en',
'faker_locale' => 'lt_LT',
'locales' => [
'lt' => 'Lietuvių',
'en' => 'English',
'ru' => 'Русский',
],
'faker_locales' => [
'lt' => 'lt_LT',
'en' => 'en_US',
'ru' => 'ru_RU',
],
helpers.php
if (! function_exists('faker_translation')) {
function faker_translation($property = 'name')
{
$fakerLocales = config('app.faker_locales');
return collect(config('app.locales'))
->map(fn ($locale, $key) => faker($fakerLocales[$key])->unique()->$property)
->toArray();
}
}
composer.json
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
},
"files": [
"app/helpers.php"
]
},
After some experimenting I've found a solution, here it is:
$factory->define(App\Category::class, function (Faker $faker) {
static $counter = 1;
$locales = Language::pluck('lang');
$titles = array('slug' => 'CATEGORY-'.$counter);
foreach ($locales as $locale) {
$titles[$locale] = [
'title' => 'Title for category-' .$counter. ' on '. $locale . ' language'
];
}
$counter++;
return $titles;
});
Related
I am using Laravel-8 and Maatwebsite-3.1 package for excel upload:
I have this Excel sheet (The data is more thank that):
imports:
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Row;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use Maatwebsite\Excel\DefaultValueBinder;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Concerns\SkipsErrors;
use Maatwebsite\Excel\Concerns\SkipsOnError;
use Maatwebsite\Excel\Concerns\SkipsFailures;
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Validators\Failure;
use Throwable;
class EmployeeImport extends DefaultValueBinder implements OnEachRow, WithStartRow, SkipsOnError, WithValidation, SkipsOnFailure, WithEvents, WithCustomValueBinder
{
// set the preferred date format
private $date_format = 'Y-m-d';
// set the columns to be formatted as
private $date_columns = ['E'];
use Importable, SkipsErrors, SkipsFailures;
public function onRow(Row $row)
{
$rowIndex = $row->getIndex();
if($rowIndex >= 1000)
return; // Not more than 1000 rows at a time
$row = $row->toArray();
$employee_data = [
'first_name' => $row[0],
'other_name' => $row[1] ?? '',
'last_name' => $row[2],
'email' => preg_replace('/\s+/', '', strtolower($row[3])),
'dob' => $this->transformDate($row[4]),
];
$employee = create(Employee::class, $employee_data);
if (User::where('email', '=', $employee->email)->exists()) {
$user = User::update([
'first_name' => $employee->first_name,
'last_name' => $employee->last_name,
'active' => 1,
]);
}else{
$user = User::create([
'email' => $employee->email,
'first_name' => $employee->first_name,
'last_name' => $employee->last_name,
'active' => 1,
]);
}
$employee->update([
'user_id' => $user->id,
]);
}
public function startRow(): int
{
return 2;
}
public function customValidationAttributes()
{
return [
'0' => 'First Name',
'1' => 'Other Name',
'2' => 'Last Name',
'3' => 'Email',
'4' => 'Date of Birth',
];
}
public function rules(): array
{
return [
'*.0' => [
'required',
'string',
'max:50'
],
'*.1' => [
'nullable',
'string',
'max:50'
],
'*.2' => [
'required',
'string',
'max:50'
],
'*.3' => [
'required',
'email',
'max:100',
Rule::unique('employees', 'email')->where(function ($query) {
return $query->where('company_id', Auth::user()->company_id);
})
],
'*.4' => [
'required',
'date_format:Y-m-d',
'before:' . Carbon::now()->subYears(18)->format('Y-m-d')
],
];
}
public function chunkSize(): int
{
return 1000;
}
public function transformDate($value, $format = 'Y-m-d')
{
try {
return \Carbon\Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value));
} catch (\ErrorException $e) {
return \Carbon\Carbon::createFromFormat($format, $value);
}
}
}
Controller:
public function importEmployee(Request $request)
{
$validator = Validator::make($request->all(), [
'document' => 'file|mimes:xls,xlsx|max:5000',
]);
if ($request->hasFile('document'))
{
if($validator->passes()) {
$import = new EmployeeImport;
$file = $request->file('document');
$file->move(public_path('storage/employee_imports'), $file->getClientOriginalName());
Excel::import($import, public_path('storage/employee_imports/' . $file->getClientOriginalName() ));
return $this->success('Employees Imported.', [
'file' => $file
]);
}else{
return $this->error($validator->errors(), 422);
}
}
}
When I submitted, I got this error:
[2021-08-19 09:33:40] local.ERROR: Error: Call to undefined function
App\Imports\create() in
C:\xampp\htdocs\myapp\app\Imports\EmployeeImport.php:98
Stack trace:
#0 C:\xampp\htdocs\myapp\vendor\maatwebsite\excel\src\Sheet.php(301):
App\Imports\EmployeeImport->onRow(Array)
#1 C:\xampp\htdocs\myapp\vendor\maatwebsite\excel\src\Reader.php(114): Maatwebsite\Excel\Sheet->import(Object(App\Imports\EmployeeImport), 2)
#2
C:\xampp\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Database\Concerns\ManagesTransactions.php(29): Maatwebsite\Excel\Reader->Maatwebsite\Excel{closure}(Object(Illuminate\Database\MySqlConnection))
This is the line 98:
$employee = create(Employee::class, $employee_data);
How do I resolve this?
Thanks
Change this line
$employee = create(Employee::class, $employee_data);
to
$employee = Employee::create($employee_data);
create is not a function alone. Check this link
https://laravel.com/docs/8.x/eloquent#inserting-and-updating-models
What is the correct way to validate that a param in the request should be in the following format: array with a key of a certain value, and a boolean value:
"countries" => array:2 [
"usa" => true
"canada" => true
]
In my Form Request I have the following rule:
public function rules()
{
return [
'countries' => ['bail', 'array'],
'countries.*' => ['string', new ValidateCountries],
'countries.*.' => ['boolean'],
];
}
My ValidateCountries passes() method:
public function passes($attribute, $value)
{
$countries = ["usa", "canada", "uk", "france"];
return in_array(strtolower($value), $countries);
}
Got it by accessing the $attribute param instead of the $value. Easy one, but my brain is fried.
public function passes($attribute, $value)
{
$attribute = explode(".", $attribute)[1];
$countries = ["usa", "canada", "france", "uk"];
return in_array(strtolower($attribute), $countries);
}
i'm working on a graphql API using Laravel GraphQL.
As shown in the documentation "Privacy" section, it should be possible to add callback function to a GraphQLType fields privacy attribute. The field is supposed to return null, when the callback returns false.
Similar to the example in the laravel graphql Docs, i've added a privacy callback like so:
public function fields(): array {
return [
'email' => [
'type' => Type::string(),
'description' => 'The email of user',
'privacy' => function(User $user): bool {
return $user->isMe();
}
],
];
}
It appears to me, that this callback function never gets called.
I read something about a possible requirement, that i should resolve my query using the $getSelectFields function to query the $fields manually $with the selected columns. But unfortunately the $select
public function resolve($root, $args, $context, ResolveInfo $info, Closure $getSelectFields) {
$fields = $getSelectFields();
$with = $fields->getRelations(); // empty array
$select = $fields->getSelect(); // empty array
return User::select($select)->with($with)->get();
}
In my case this does not make any difference.
In my query resolver i do as following:
public function resolve($root, $args, $context, ResolveInfo $info, Closure $getSelectFields) {
/** #var SelectFields $fields */
$fields = $getSelectFields();
$select = $fields->getSelect();
$with = $fields->getRelations();
exit(var_dump($fields)); // #RESULT
}
My result looks like this:
object(Rebing\\GraphQL\\Support\\SelectFields)#4668 (2) {
[\"select\":\"Rebing\\GraphQL\\Support\\SelectFields\":private]=> array(0) {}
[\"relations\":\"Rebing\\GraphQL\\Support\\SelectFields\":private]=> array(0) {}
}
So my question is: "How do i use the privacy attribute callback in Laravel Rebing GraphQL?"
I'm using:
PHP 7.3
Laravel 7.17
Rebing Graphql Laravel 5.1
Thanks in advance,
greets Jules
Some more Details about my use case
EpUser.php
namespace App\GraphQL\Type;
use App\CommunityImage;
use App\User;
use Carbon\Carbon;
use GraphQL\Type\Definition\Type;
use Illuminate\Support\Facades\Auth;
use Rebing\GraphQL\Support\Facades\GraphQL;
use Rebing\GraphQL\Support\Type as GraphQLType;
class EpUser extends GraphQLType {
protected $attributes = [
'name' => 'EpUser',
'description' => 'A type',
'model' => User::class,
];
public function fields(): array {
return [
'id' => [
'type' => Type::nonNull(Type::int()),
'description' => 'The id of the user',
'privacy' => function(User $user): bool {
return false;
}
],
'email' => [
'type' => Type::string(),
'description' => 'The email of user',
'privacy' => function(User $user): bool {
return $user->isMe();
}
],
'firstName' => [
'type' => Type::string(),
'description' => 'The firstName of user'
],
'lastName' => [
'type' => Type::string(),
'description' => 'The lastName of user'
],
'fullName' => [
'type' => Type::string(),
'description' => 'The fullName of user',
'selectable' => false,
'resolve' => function(User $user) {
return $user->firstName . " " . $user->lastName;
}
],
'gender' => [
'type' => Type::string(),
'description' => 'The gender of the user'
],
'isOnline' => [
'type' => Type::boolean(),
'description' => '',
'selectable' => false,
'resolve' => function(User $user, $args) {
return $user->isOnline();
}
]
];
}
[...]
And this is the UsersQuery which should respond with a user pagination object, that contains an array of users with a privacy attribute:
UsersQuery.php
namespace App\GraphQL\Query;
use App\Artist;
use App\FilePath;
use Closure;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Query;
use Illuminate\Support\Facades\Auth;
use GraphQL\Type\Definition\ResolveInfo;
use Rebing\GraphQL\Support\Facades\GraphQL;
use App\User;
class UsersQuery extends Query {
protected $attributes = [
'name' => 'UsersQuery',
'description' => 'A query',
'model' => User::class,
];
public function type(): Type {
return GraphQL::type('userPagination');
}
public function authorize($root, array $args, $ctx, ResolveInfo $resolveInfo = NULL, $getSelectFields = NULL): bool {
return Auth::check();
}
public function args(): array {
return [
'id' => [
'type' => Type::int(),
'description' => 'The id of the user'
],
'slug' => [
'type' => Type::string(),
'description' => 'The slug of the user'
],
'pagination' => [
'type' => Type::nonNull(GraphQL::type('paginationInput')),
'description' => 'The pagination of the users to query',
'rules' => 'required',
],
'search' => [
'type' => Type::string(),
'description' => 'a string to search for users'
],
'roles' => [
'type' => Type::listOf(Type::string()),
'description' => 'The roles of the user',
'rules' => 'sometimes|required|array|in:user,developer,administrator'
]
];
}
public function resolve($root, $args, $context, ResolveInfo $info, Closure $getSelectFields) {
if(isset($args['id']) || isset($args['slug'])) {
if(isset($args['slug'])) {
$user = User::where('slug', $args['slug'])->first();
} else {
$user = User::find($args['id']);
}
return [
'items' => $args['pagination']['limit'] > 0 && $user ? [$user] : NULL,
'itemTotal' => $user ? 1 : 0
];
}
$sortBy = $args['pagination']['sortBy'] ?? 'id';
$sortByDesc = isset($args['pagination']['sortByDesc']) ? $args['pagination']['sortByDesc'] : true;
$sortByType = $sortByDesc ? 'desc' : 'asc';
$search = false;
if(isset($args['search']) && $args['search']) {
$search = true;
$query = User::search($args['search']);
} else {
$query = User::query();
}
if(!empty($sortBy)) {
$query->orderBy($sortBy, $sortByType);
}
// Todo: eloquent search can't serach for whereHas
if(isset($args['roles']) && !$search) {
if(is_array($args['roles'])) {
foreach($args['roles'] as &$role) {
$query->whereHas('roles',
function($q) use ($role) {
$q->where('name', $role);
});
}
} else {
$query->whereHas('roles',
function($q) use ($args) {
$q->where('name', $args['roles']);
});
}
}
if($search) {
$userPaginationObject = [
'itemTotal' => $query->count(),
'items' => $query->getWithLimitAndOffset($args['pagination']['limit'],
$args['pagination']['offset'])
];
} else {
$userPaginationObject = [
'itemTotal' => $query->count(),
'items' => $query->limit($args['pagination']['limit'])->offset($args['pagination']['offset'])->get()
];
}
return $userPaginationObject;
}
}
I have problem when testing validating using data provider..
When i use translation helper the test not execute but when use normal text (string) the testing run normal...
But i want use translation helper to easy maintenance in future...
Here my example code :
/**
* #dataProvider validateFirstNameProvider
*/
public function testStoreValidation($attribute, $value, $message)
{
$response = $this->actingAs($this->user)
->post(route('user.store'), [
$attribute=> $value,
]);
$response->assertSessionHasErrorsIn('validation', [
$attribute => $message,
]);
}
public function validateFirstNameProvider()
{
return [
'required first name' => [
'first_name',
'',
trans('validation.required', [
'attribute' => trans('validation.attributes.first_name'),
]),
],
];
}
Code without use translation helper :
public function validateFirstNameProvider()
{
return [
'required first name' => [
'first_name',
'',
'The first name field is required.',
],
];
}
Im have a problem in Yii.
Example:
There are CRUDs for Customers and for Joboffers. I want to click on a create button on the Customer-Index that redirect me to the Joboffer-Create-Form where the ID from the Employee wich i clicked on is accessable. Any tips that send me on the right way?
<?php
/* #var $this yii\web\View */
/* #var $searchModel app\models\CustomersSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
use yii\helpers\Html;
use yii\helpers\Url;
use kartik\export\ExportMenu;
use kartik\grid\GridView;
$this->title = Yii::t('app', 'Customers');
$this->params['breadcrumbs'][] = $this->title;
$search = "$('.search-button').click(function(){
$('.search-form').toggle(1000);
return false;
});";
$this->registerJs($search);
?>
<div class="customers-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a(Yii::t('app', 'Create Customers'), ['create'], ['class' => 'btn btn-success']) ?>
<?= Html::a(Yii::t('app', 'Advance Search'), '#', ['class' => 'btn btn-info search-button']) ?>
</p>
<div class="search-form" style="display:none">
<?= $this->render('_search', ['model' => $searchModel]); ?>
</div>
<?php
$gridColumn = [
'id_kunde',
[
'label' => 'Kunde',
'attribute' => 'id_kunde',
'format' => 'raw',
'value' => function($model){
if($model->webseite == "") {
return '<div>'.$model->firma.'<br>'.$model->created_at.'<br>'.$model->contactPeople->vorname.' '.$model->contactPeople->nachname.'<br>'.$model->contactPeople->geschaeftsadresse_email_1.'<br>'.$model->contactPeople->geschaeftsadresse_mobil.'</div>';
} else {
return '<div>'.$model->firma.'<br>'.Html::a('<small class="btn btn-sm btn-primary">'.$model->webseite.'</small>', $model->webseite, ['target'=>'_blank'], ['class' => 'btn btn-danger']).'<br>'.$model->contactPeople->vorname.' '.$model->contactPeople->nachname.'<br>'.$model->contactPeople->geschaeftsadresse_email_1.'<br>'.$model->contactPeople->geschaeftsadresse_mobil.'</div>';
}
},
'filterType' => GridView::FILTER_SELECT2,
'filter' => \yii\helpers\ArrayHelper::map(\app\models\Customers::find()->asArray()->all(), 'id_kunde', 'firma'),
'filterWidgetOptions' => [
'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => 'Kunden auswählen', 'id' => 'grid-customers-search-id_ansprwechpartner']
],
[
'attribute' => 'id_mitarbeiter',
'label' => Yii::t('app', 'Id Mitarbeiter'),
'value' => function($model){
return $model->mitarbeiter->id_mitarbeiter;
},
'filterType' => GridView::FILTER_SELECT2,
'filter' => \yii\helpers\ArrayHelper::map(\app\models\Employee::find()->asArray()->all(), 'id_mitarbeiter', 'id_mitarbeiter'),
'filterWidgetOptions' => [
'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => 'Pers tbl employee', 'id' => 'grid-customers-search-id_mitarbeiter']
],
'interner_hinweis',
['attribute' => 'lock', 'visible' => false],
[
'class' => 'yii\grid\ActionColumn',
'template' => '{create}',
'contentOptions'=>['style'=>'width: 25px;'],
'buttons' => [
'create' => function ($url, $index, $key) {
return Html::a('<span class="glyphicon glyphicon-copy"></span>', Url::to(['joboffer/create', 'id' => $this->id_kunde]), ['title' => 'Create Joboffer']);
},
],
],
[
'class' => 'yii\grid\ActionColumn',
'template' => '{save-as-new} {view} {update} {delete}',
'buttons' => [
'save-as-new' => function ($url) {
return Html::a('<span class="glyphicon glyphicon-copy"></span>', $url, ['title' => 'Save As New']);
},
],
],
];
?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => $gridColumn,
'pjax' => true,
'pjaxSettings' => ['options' => ['id' => 'kv-pjax-container-customers']],
// your toolbar can include the additional full export menu
'toolbar' => [
'{export}',
ExportMenu::widget([
'dataProvider' => $dataProvider,
'columns' => $gridColumn,
'target' => ExportMenu::TARGET_BLANK,
'fontAwesome' => true,
'dropdownOptions' => [
'label' => 'Full',
'class' => 'btn btn-default',
'itemsBefore' => [
'<li class="dropdown-header">Export All Data</li>',
],
],
]) ,
],
]); ?>
</div>
<?php
namespace app\controllers;
use Yii;
use app\models\Customers;
use app\models\CustomersSearch;
use app\models\Joboffer;
use app\models\JobofferSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* CustomersController implements the CRUD actions for Customers model.
*/
class CustomersController extends Controller
{
public $param = '';
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
'access' => [
'class' => \yii\filters\AccessControl::className(),
'rules' => [
[
'allow' => true,
'actions' => ['joboffer','index', 'view', 'create', 'update', 'delete', 'pdf', 'save-as-new', 'add-application', 'add-contact-person', 'add-job-suggestion', 'add-joboffer'],
'roles' => ['#']
],
[
'allow' => false
]
]
]
];
}
/**
* Lists all Customers models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new CustomersSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Customers model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
$model = $this->findModel($id);
$providerApplication = new \yii\data\ArrayDataProvider([
'allModels' => $model->applications,
]);
$providerContactPerson = new \yii\data\ArrayDataProvider([
'allModels' => $model->contactPeople,
]);
$providerJobSuggestion = new \yii\data\ArrayDataProvider([
'allModels' => $model->jobSuggestions,
]);
$providerJoboffer = new \yii\data\ArrayDataProvider([
'allModels' => $model->joboffers,
]);
return $this->render('view', [
'model' => $this->findModel($id),
'providerApplication' => $providerApplication,
'providerContactPerson' => $providerContactPerson,
'providerJobSuggestion' => $providerJobSuggestion,
'providerJoboffer' => $providerJoboffer,
]);
}
/**
* Creates a new Customers model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Customers();
if ($model->loadAll(Yii::$app->request->post()) && $model->saveAll()) {
return $this->redirect(['view', 'id' => $model->id_kunde]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Customers model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
if (Yii::$app->request->post('_asnew') == '1') {
$model = new Customers();
}else{
$model = $this->findModel($id);
}
if ($model->loadAll(Yii::$app->request->post()) && $model->saveAll()) {
return $this->redirect(['view', 'id' => $model->id_kunde]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Customers model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->deleteWithRelated();
return $this->redirect(['index']);
}
/**
*
* Export Customers information into PDF format.
* #param integer $id
* #return mixed
*/
public function actionPdf($id) {
$model = $this->findModel($id);
$providerApplication = new \yii\data\ArrayDataProvider([
'allModels' => $model->applications,
]);
$providerContactPerson = new \yii\data\ArrayDataProvider([
'allModels' => $model->contactPeople,
]);
$providerJobSuggestion = new \yii\data\ArrayDataProvider([
'allModels' => $model->jobSuggestions,
]);
$providerJoboffer = new \yii\data\ArrayDataProvider([
'allModels' => $model->joboffers,
]);
$content = $this->renderAjax('_pdf', [
'model' => $model,
'providerApplication' => $providerApplication,
'providerContactPerson' => $providerContactPerson,
'providerJobSuggestion' => $providerJobSuggestion,
'providerJoboffer' => $providerJoboffer,
]);
$pdf = new \kartik\mpdf\Pdf([
'mode' => \kartik\mpdf\Pdf::MODE_CORE,
'format' => \kartik\mpdf\Pdf::FORMAT_A4,
'orientation' => \kartik\mpdf\Pdf::ORIENT_PORTRAIT,
'destination' => \kartik\mpdf\Pdf::DEST_BROWSER,
'content' => $content,
'cssFile' => '#vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
'cssInline' => '.kv-heading-1{font-size:18px}',
'options' => ['title' => \Yii::$app->name],
'methods' => [
'SetHeader' => [\Yii::$app->name],
'SetFooter' => ['{PAGENO}'],
]
]);
return $pdf->render();
}
/**
* Creates a new Customers model by another data,
* so user don't need to input all field from scratch.
* If creation is successful, the browser will be redirected to the 'view' page.
*
* #param type $id
* #return type
*/
public function actionSaveAsNew($id) {
$model = new Customers();
if (Yii::$app->request->post('_asnew') != '1') {
$model = $this->findModel($id);
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id_kunde]);
} else {
return $this->render('saveAsNew', [
'model' => $model,
]);
}
}
/**
* Finds the Customers model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Customers the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Customers::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
/**
* Action to load a tabular form grid
* for Application
* #author Yohanes Candrajaya <moo.tensai#gmail.com>
* #author Jiwantoro Ndaru <jiwanndaru#gmail.com>
*
* #return mixed
*/
public function actionAddApplication()
{
if (Yii::$app->request->isAjax) {
$row = Yii::$app->request->post('Application');
if((Yii::$app->request->post('isNewRecord') && Yii::$app->request->post('_action') == 'load' && empty($row)) || Yii::$app->request->post('_action') == 'add')
$row[] = [];
return $this->renderAjax('_formApplication', ['row' => $row]);
} else {
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
/**
* Action to load a tabular form grid
* for ContactPerson
* #author Yohanes Candrajaya <moo.tensai#gmail.com>
* #author Jiwantoro Ndaru <jiwanndaru#gmail.com>
*
* #return mixed
*/
public function actionAddContactPerson()
{
if (Yii::$app->request->isAjax) {
$row = Yii::$app->request->post('ContactPerson');
if((Yii::$app->request->post('isNewRecord') && Yii::$app->request->post('_action') == 'load' && empty($row)) || Yii::$app->request->post('_action') == 'add')
$row[] = [];
return $this->renderAjax('_formContactPerson', ['row' => $row]);
} else {
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
/**
* Action to load a tabular form grid
* for JobSuggestion
* #author Yohanes Candrajaya <moo.tensai#gmail.com>
* #author Jiwantoro Ndaru <jiwanndaru#gmail.com>
*
* #return mixed
*/
public function actionAddJobSuggestion()
{
if (Yii::$app->request->isAjax) {
$row = Yii::$app->request->post('JobSuggestion');
if((Yii::$app->request->post('isNewRecord') && Yii::$app->request->post('_action') == 'load' && empty($row)) || Yii::$app->request->post('_action') == 'add')
$row[] = [];
return $this->renderAjax('_formJobSuggestion', ['row' => $row]);
} else {
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
/**
* Action to load a tabular form grid
* for Joboffer
* #author Yohanes Candrajaya <moo.tensai#gmail.com>
* #author Jiwantoro Ndaru <jiwanndaru#gmail.com>
*
* #return mixed
*/
public function actionAddJoboffer()
{
if (Yii::$app->request->isAjax) {
$row = Yii::$app->request->post('Joboffer');
if((Yii::$app->request->post('isNewRecord') && Yii::$app->request->post('_action') == 'load' && empty($row)) || Yii::$app->request->post('_action') == 'add')
$row[] = [];
return $this->renderAjax('_formJoboffer', ['row' => $row]);
} else {
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
}
You should use the function for returning the HTML code
function ($url, $model, $key) {
// return the button HTML code
}
this way
[
'class' => 'yii\grid\ActionColumn',
'template' => '{create}',
'contentOptions'=>['style'=>'width: 25px;'],
'buttons' => [
'create' => function ($url, $model, $key) {
return Html::a('<span class="glyphicon glyphicon-copy"></span>',
Url::to(['joboffer/create',
'id' => $model->id_kunde]), ['title' => 'Create Joboffer']);
},
],
],