Object of Class App\PageStatus (DateTime?) could not be converted to int - php

I am using nova-dependency-container but get the following error Object of Class App\PageStatus could not be converted to int. This error appears when creating a new page/resource in Laravel Nova or when trying to view a page/resource in Laravel Nova.
However, the page/resource still gets created... but when trying to view the page/resource I just get this error and see a blank page...
This is my app/Nova/Page.php model
<?php
namespace App\Nova;
use Epartment\NovaDependencyContainer\HasDependencies;
use Epartment\NovaDependencyContainer\NovaDependencyContainer;
use Froala\NovaFroalaField\Froala;
use Gwd\SeoMeta\SeoMeta;
use Illuminate\Http\Request;
use Inspheric\Fields\Indicator;
use Laravel\Nova\Fields\BelongsTo;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Fields\DateTime;
use App\PageStatus;
class Page extends Resource
{
use HasDependencies;
/**
* The model the resource corresponds to.
*
* #var string
*/
public static $model = \App\Page::class;
/**
* The single value that should be used to represent the resource when being displayed.
*
* #var string
*/
public static $title = 'title';
/**
* The columns that should be searched.
*
* #var array
*/
public static $search = [
'title',
'slug'
];
/**
* The logical group associated with the resource.
*
* #var string
*/
public static $group = 'Pages & Posts';
/**
* Get the fields displayed by the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function fields(Request $request)
{
return [
ID::make('ID', 'id')->asBigInt(),
Text::make('Title')
->rules('required', 'max:255'),
Text::make('Slug', 'slug')
->hideFromIndex()
->creationRules('unique:pages,slug')
->rules('required', 'alpha_dash', 'max:80'),
Froala::make('Content')
->hideFromIndex()
->rules('required'),
Indicator::make('Status', function() {
return $this->pageStatus->status;
})
->labels([
'publish' => 'Publish',
'future' => 'Future',
'draft' => 'Draft',
'pending' => 'Pending',
'private' => 'Privat'
])
->colors([
'publish' => 'green',
'future' => 'purple',
'draft' => 'blue',
'pending' => 'orange',
'private' => 'red'
]),
BelongsTo::make('Status', 'pageStatus', 'App\Nova\PageStatus')
->onlyOnForms(),
NovaDependencyContainer::make([
DateTime::make('When to Publish', 'publish_at')
->format('DD.MM.YYYY # HH:MM:SS')
->rules('required', 'date_format:Y-m-d H:i:s')
])->dependsOn('pageStatus', PageStatus::getIdByStatus('future')),
BelongsTo::make('Author', 'user', 'App\Nova\User'),
SeoMeta::make('SEO', 'seo_meta'),
];
}
/**
* Get the cards available for the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function cards(Request $request)
{
return [];
}
/**
* Get the filters available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function filters(Request $request)
{
return [];
}
/**
* Get the lenses available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function lenses(Request $request)
{
return [];
}
/**
* Get the actions available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function actions(Request $request)
{
return [];
}
}
app/Nova/PageStatus.php model:
<?php
namespace App\Nova;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Http\Requests\NovaRequest;
class PageStatus extends Resource
{
/**
* The model the resource corresponds to.
*
* #var string
*/
public static $model = \App\PageStatus::class;
/**
* The single value that should be used to represent the resource when being displayed.
*
* #var string
*/
public static $title = 'label';
/**
* The columns that should be searched.
*
* #var array
*/
public static $search = [
'status', 'label'
];
/**
* Default ordering for index query.
*
* #var array
*/
public static $sort = [
'id' => 'asc'
];
/**
* The logical group associated with the resource.
*
* #var string
*/
public static $group = 'Pages & Posts';
/**
* Build an "index" query for the given resource.
*
* #param \Laravel\Nova\Http\Requests\NovaRequest $request
* #param \Illuminate\Database\Eloquent\Builder $query
* #return \Illuminate\Database\Eloquent\Builder
*/
public static function indexQuery(NovaRequest $request, $query)
{
if (empty($request->get('orderBy'))) {
$query->getQuery()->orders = [];
return $query->orderBy(key(static::$sort), reset(static::$sort));
}
return $query;
}
/**
* Get the fields displayed by the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Text::make('Status', 'status')
->required(),
Text::make('Label', 'label')
->required(),
];
}
/**
* Get the cards available for the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function cards(Request $request)
{
return [];
}
/**
* Get the filters available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function filters(Request $request)
{
return [];
}
/**
* Get the lenses available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function lenses(Request $request)
{
return [];
}
/**
* Get the actions available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function actions(Request $request)
{
return [];
}
}
App/Page.php model:
<?php
namespace App;
use Gwd\SeoMeta\Traits\SeoSitemapTrait;
use Illuminate\Database\Eloquent\Model;
use Gwd\SeoMeta\Traits\SeoMetaTrait;
class Page extends Model
{
use SeoMetaTrait, SeoSitemapTrait;
/*
* In order to have set the auth user as default user when creating a page
*/
public function __construct(array $attributes = [])
{
if (! isset($attributes['user_id']) && auth()->check()) {
$attributes['user_id'] = auth()->user()->id;
}
parent::__construct($attributes);
}
/**
* #Protected_variables
*/
protected $table = 'pages';
protected $guarded = ['id'];
protected $casts = [
'publish_at' => 'datetime',
'created_at' => 'datetime',
'updated_at' => 'datetime'
];
/**
* #Public_variables
*/
/**
* #Relationships
*/
public function user()
{
return $this->belongsTo('App\User');
}
public function pageStatus()
{
return $this->belongsTo('App\PageStatus');
}
/**
* #Attributes
*/
/**
* #Custom_functions
*/
/**
* Get the Page url by item
*
* #return string
*/
public function getSitemapItemUrl(): String
{
return route('page.show', $this->slug);
}
/**
* Query all the Page items which should be
* part of the sitemap (crawlable for google).
*
* #return Page[]|\Illuminate\Database\Eloquent\Collection
*/
public static function getSitemapItems()
{
return static::all();
}
}
App/PageStatus.php model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PageStatus extends Model
{
/**
* #Protected_variables
*/
protected $table = 'page_statuses';
protected $guarded = ['id'];
/**
* #Public_variables
*/
/**
* #Relationships
*/
public function products()
{
return $this->hasMany('App\Product');
}
/**
* #Attributes
*/
/**
* #Custom_functions
*/
public static function getPageStatusesFilterArray()
{
$page_statuses = PageStatus::all('id', 'label');
$array = array();
foreach($page_statuses as $page_status){
$array[$page_status->label] = $page_status->id;
}
return $array;
}
public static function getIdByStatus($status)
{
return self::where('status', $status)->first()->id;
}
}
Update
pageStatus migration file:
class CreatePageStatusesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('page_statuses', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('status')->index()->unique();
$table->string('label');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('page_statuses');
}
}

I found the problem. I have to change ->dependsOn('pageStatus', PageStatus::getIdByStatus('future')) to ->dependsOn('pageStatus.id', PageStatus::getIdByStatus('future')).
The .id was missing to specify the column of the postStatus.

Related

Laravel Nova pass value of one filter to another filter

I am trying to filter Laravel Nova resource (Reviews) data using 2 'select-filters'.
I have a filter A = Manufacturers and filter B = Models.
A Manufacturer has many Models. I have manufacturer and model column in products table.
'Model' filter by default show all the values in the select dropdown. I want to reduce the select options in the 'Model' filter when 'Manufacturer' is selected.
so, for example: When Manufacturer = "Apple" then 'Model' filter should show only Apple 'Models'.
In my Review Resource, I have below code:
/**
* Get the filters available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function filters(Request $request)
{
return [
new Manufacturer(),
new Model(),
];
}
Manufacturer Filter code
class Manufacturer extends Filter
{
/**
* The filter's component.
*
* #var string
*/
public $component = 'select-filter';
/**
* Apply the filter to the given query.
*
* #param \Illuminate\Http\Request $request
* #param \Illuminate\Database\Eloquent\Builder $query
* #param mixed $value
*
* #return \Illuminate\Database\Eloquent\Builder
*/
public function apply(Request $request, $query, $value)
{
return $query->whereHas('product', function ($query) use ($value) {
$query->where('manufacturer', $value);
});
}
/**
* Get the filter's available options.
*
* #param \Illuminate\Http\Request $request
*
* #return array
*/
public function options(Request $request)
{
return Product::select('manufacturer')
->withoutGlobalScopes()
->withoutTrashed()
->groupBy('manufacturer')
->orderBy('manufacturer')
->pluck('manufacturer')
->mapWithKeys(function ($manufacturer) {
return [$manufacturer => strtolower($manufacturer)];
})
->toArray();
}
}
Model Filter code
class Model extends Filter
{
/**
* The filter's component.
*
* #var string
*/
public $component = 'select-filter';
/**
* Apply the filter to the given query.
*
* #param \Illuminate\Http\Request $request
* #param \Illuminate\Database\Eloquent\Builder $query
* #param mixed $value
*
* #return \Illuminate\Database\Eloquent\Builder
*/
public function apply(Request $request, $query, $value)
{
return $query->whereHas('product', function ($query) use ($value) {
$query->where('model', $value);
});
}
/**
* Get the filter's available options.
*
* #param \Illuminate\Http\Request $request
*
* #return array
*/
public function options(Request $request)
{
//
//
//I want to add a condition below ->where('manufacturer', $manufacturer)
//
//
return Product::select('model')
->withoutGlobalScopes()
->withoutTrashed()
->groupBy('model')
->orderBy('model')
->pluck('model')
->mapWithKeys(function ($model) {
return [$model => strtolower($model)];
})
->toArray();
}
}
I tried to decode $request to get the filter values but returns null.
I found the library that helps achieve exactly what I wanted.
The library can be found here: https://github.com/awesome-nova/dependent-filter
Once the above library is installed, the two filters can be set as shown below:
Filter A
<?php
namespace App\Nova\Filters;
use Illuminate\Http\Request;
use App\Models\Product;
use AwesomeNova\Filters\DependentFilter;
class Manufacturer extends DependentFilter
{
/**
* Name of filter.
*
* #var string
*/
public $name = 'Manufacturer';
/**
* Attribute name of filter. Also it is key of filter.
*
* #var string
*/
public $attribute = 'manufacturer';
/**
* The filter's component.
*
* #var string
*/
public $component = 'awesome-nova-dependent-filter';
/**
* Apply the filter to the given query.
*
* #param \Illuminate\Http\Request $request
* #param \Illuminate\Database\Eloquent\Builder $query
* #param mixed $value
* #return \Illuminate\Database\Eloquent\Builder
*/
public function apply(Request $request, $query, $value)
{
return $query->whereHas('product', function ($query) use ($value) {
$query->where('manufacturer', $value);
});
}
/**
* Get the filter's available options.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function options(Request $request, array $filters = [])
{
return Product::select('manufacturer')
->pluck('manufacturer')
->mapWithKeys(function ($manufacturer) {
return [$manufacturer => $manufacturer];
})->toArray();
}
Filter B
<?php
namespace App\Nova\Filters;
use App\Models\Product;
use Illuminate\Http\Request;
use AwesomeNova\Filters\DependentFilter;
class Model extends DependentFilter
{
/**
* Name of filter.
*
* #var string
*/
public $name = 'Model';
/**
* Attribute name of filter. Also it is key of filter.
*
* #var string
*/
public $attribute = 'model';
/**
* The filter's component.
*
* #var string
*/
public $component = 'awesome-nova-dependent-filter';
/**
* The filter's dependentOf.
*
* #var array
*/
public $dependentOf = ['manufacturer'];
public $hideWhenEmpty = true;
/**
* Apply the filter to the given query.
*
* #param \Illuminate\Http\Request $request
* #param \Illuminate\Database\Eloquent\Builder $query
* #param mixed $value
* #return \Illuminate\Database\Eloquent\Builder
*/
public function apply(Request $request, $query, $value)
{
return $query->whereHas('product', function ($query) use ($value) {
$query->where('model', $value);
});
}
/**
* Get the filter's available options.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function options(Request $request, array $filters = [])
{
return Product::select('model')
->where('manufacturer', $filters['manufacturer'])
->pluck('model')
->mapWithKeys(function ($model) {
return [$model => $model];
})->toArray();
}
}
Resource File
public function filters(Request $request)
{
return [
Manufacturer::make(),
Model::make(),
];
}

Incompatible repository declarations using pattern design but only in server in Laravel 7

I have an application in my local environment and in a production server. This application have a controller called ArticlesController with this code:
<?php
namespace App\Admin\Controllers;
use App\Core\Controllers\CoreController;
use App\Admin\Requests\ArticlesRequest;
use App\Admin\Interfaces\ArticlesRepositoryInterface;
class ArticlesController extends CoreController
{
/**
* #var ArticlesRepositoryInterface
*/
private $articleRepository;
public function __construct(ArticlesRepositoryInterface $articleRepository)
{
$this->articleRepository = $articleRepository;
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\View\View
*/
public function index()
{
$articles = $this->articleRepository->all();
return view('admin.articles.index')->with(compact('articles'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\View\View
*/
public function create()
{
return view('admin.articles.create');
}
/**
* Store a newly created resource in storage.
*
* #param \App\Admin\Requests\ArticlesRequest $request
* #return \Illuminate\Routing\Redirector
*/
public function store(ArticlesRequest $request)
{
$data = $request->validated();
$article = $this->articleRepository->create($data);
return redirect()->route('articles.edit', $article)->with('successMessage', 'Article created! Now you can edit the article with new information');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show(int $id)
{
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$article = $this->articleRepository->find($id);
return view('admin.articles.edit')->with(compact('article'));
}
/**
* Update the specified resource in storage.
*
* #param \App\Admin\Requests\ArticlesRequest $request
* #param int $id
* #return \Illuminate\Routing\Redirector
*/
public function update(ArticlesRequest $request, int $id)
{
$data = $request->validated();
$this->articleRepository->update($data, $id);
return redirect()->route('articles.index')->with('successMessage', 'Article updated!');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$this->articleRepository->delete($id);
return redirect()->route('articles.index')->with('successMessage', 'Article deleted!');;
}
}
How you can see, this controller uses ArticlesRepositoryInterface. This is the code:
<?php
namespace App\Admin\Interfaces;
use App\Admin\Models\Article;
use Illuminate\Database\Eloquent\Collection;
interface ArticlesRepositoryInterface extends BaseRepositoryInterface
{
/**
* #return Collection
*/
public function all(): Collection;
/**
* #param array $data
* #return Article
*/
public function create(array $data): Article;
/**
* #param array $data
* #param int $id
* #return int
*/
public function update(array $data, int $id): int;
/**
* #param int $id
* #return int
*/
public function delete(int $id): int;
/**
* #param int $id
* #return Article
*/
public function find(int $id): ?Article;
}
Also, I have a provider that I use to instantiate the repositories with this code:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Admin\Interfaces\BaseRepositoryInterface;
use App\Admin\Interfaces\ArticlesRepositoryInterface;
use App\Admin\Interfaces\FilesRepositoryInterface;
use App\Admin\Repositories\BaseRepository;
use App\Admin\Repositories\ArticlesRepository;
use App\Admin\Repositories\FilesRepository;
class RepositoryServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* #return void
*/
public function register()
{
$this->app->bind(BaseRepositoryInterface::class, BaseRepository::class);
$this->app->bind(ArticlesRepositoryInterface::class, ArticlesRepository::class);
$this->app->bind(FilesRepositoryInterface::class, FilesRepository::class);
}
/**
* Bootstrap services.
*
* #return void
*/
public function boot()
{
//
}
}
The code of the BaseRepository is this:
<?php
namespace App\Admin\Repositories;
use App\Admin\Interfaces\BaseRepositoryInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;
class BaseRepository implements BaseRepositoryInterface
{
/**
* #var Model
*/
protected $model;
/**
* #param Model $model
*/
public function __construct(Model $model)
{
$this->model = $model;
}
/**
* #return Collection
*/
public function all(): Collection
{
return $this->model->all();
}
/**
* #param array $data
* #return Model
*/
public function create(array $data): Model
{
return $this->model->create($data);
}
/**
* #param array $data
* #param int $id
* #return int
*/
public function update(array $data, int $id): int
{
return $this->model->where('id', $id)->update($data);
}
/**
* #param int $id
* #return int
*/
public function delete(int $id): int
{
return $this->model->destroy($id);
}
/**
* #param int $id
* #return Model
*/
public function find($id): ?Model
{
return $this->model->find($id);
}
}
And finally, the code of the ArticlesRepository is this:
<?php
namespace App\Admin\Repositories;
use App\Admin\Interfaces\ArticlesRepositoryInterface;
use App\Admin\Models\Article;
use Illuminate\Database\Eloquent\Collection;
use App\Admin\Repositories\BaseRepository;
class ArticlesRepository extends BaseRepository implements ArticlesRepositoryInterface
{
/**
* #var Article
*/
protected $article;
/**
* #param Article $article
*/
public function __construct(Article $article)
{
$this->article = $article;
}
/**
* #return Collection
*/
public function all(): Collection
{
return $this->article->all();
}
/**
* #param array $data
* #return Article
*/
public function create(array $data): Article
{
return $this->article->create($data);
}
/**
* #param array $data
* #param int $id
* #return int
*/
public function update(array $data, int $id): int
{
return $this->article->where('id', $id)->update($data);
}
/**
* #param int $id
* #return int
*/
public function delete(int $id): int
{
return $this->article->destroy($id);
}
/**
* #param int $id
* #return Article
*/
public function find($id): ?Article
{
return $this->article->find($id);
}
}
It works perfectly in my local environment, but, is strange, because in the remote server, with exactly the same code, it throws an error:
Declaration of App\Admin\Repositories\ArticlesRepository::create(array $data): App\Admin\Models\Article must be compatible with App\Admin\Repositories\BaseRepository::create(array $data): Illuminate\Database\Eloquent\Model
Any ideas?
All function declarations should be exactly the same, including the return type declarations:
ArticlesRepositoryInterface:
public function create(array $data): Article;
BaseRepository:
public function create(array $data): Model
ArticlesRepository:
public function create(array $data): Article;
App\Admin\Models\Article and Illuminate\Database\Eloquent\Model cannot be used both.
Perhaps this doesn't throw an exception locally because of a different PHP version?
Note: you might want to consider to extend all the repositories from a single BaseRepository.

Laravel "SQLSTATE[HY000]: General error: 1364 Field 'Login' doesn't have a default value..."

I was having this issue after trying all existing solutions from other threads none works, like this one : MySql Error: 1364 Field 'display_name' doesn't have default value if i do ->nullable() all my inserts would be empty.
thats my code :
The controller:
<?php
namespace App\Http\Controllers;
use App\Utilisateur;
use Illuminate\Http\Request;
class UtilisateursController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('login.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'username' => 'required',
//'email' => 'required',
'password' => 'required',
//'password_confirmation' => 'required',
//'telephone' => 'required'
]);
$inscription = new Utilisateur([
'Login' => $request->get('username'),
'E-mail' => 'email',
'Password' => $request->get('password'),
'Telephone' => 'telephone',
'created_at' => $request->get(date("Y-m-d H:i:s")),
'updated_at' => $request->get(date("Y-m-d H:i:s"))
]);
$inscription->save();
return redirect()->route('login.create')->with('success', 'inscription réussite');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
The model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Utilisateur extends Model
{
protected $fillable = ['username', 'email', 'password', 'telephone'];
}
The database:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUtilisateursTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('utilisateurs', function (Blueprint $table) {
$table->increments('ID-User');
$table->string('Login', 250);
$table->string('Password', 250);
$table->string('Telephone', 250);
$table->string('E-mail', 250)->unique();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('utilisateurs');
}
}
Either there's a field name called display_name in your table or which should be add in the model
If you are using version laravel 5, you can try with this migration code in a separate migration file like UpdateUtilisateursColumn to update the column:
Schema::table('utilisateurs', function($table)
{
$table->string('Login', 250)->nullable()->change();
});
Finally run command: php artisan migrate
By default Laravel has many built in components in model its just the example Customize as your need i am
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
/**
* Class Utilisateur
*
* #package App
*/
class UtilisateurModel
{
/**
* The connection name for the model.
*
* #var string
*/
protected $connection ='';
/**
* The attributes that aren't mass assignable.
*
* #var array
*/
protected $guarded = ['id'];
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'utilisateurs';
/**
* The primary key for the model.
*
* #var string
*/
protected $primaryKey = 'id';
/**
* The "type" of the auto-incrementing ID.
*
* #var string
*/
protected $keyType = 'int';
/**
* Indicates if the IDs are auto-incrementing.
*
* #var bool
*/
public $incrementing = true;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [];
/**
* #var array
*/
protected $dates = ['created_at','updated_at'];
/**
* Indicates if the model should be timestamped.
*
* #var bool
*/
public $timestamps = '';
/**
* The storage format of the model's date columns.
*
* #var string
*/
protected $dateFormat ='';
}
Now Comming to the Description
if you missed any of the fileds un the fillable array the error may occur
Jusd add All Fields of the table to fillable array
$fillable = ['ID-User','Login','Password','Telephone','E-mail'];
MANIN THINGS IS IF YOU ARE USING PASSWORD FIELDS KINDLY USE THE $hidden Property
protected $hidden = ['Password'];
set login column nullable. means if no data passed for this field by default it should be always null.

Symfony - Integrity constraint violation: 1062 Duplicate entry

I tried to find an answer for my question but it was unsuccessful. I'm using Symfony (Ive been using it 2 months) and I have a problem when I want to make many to many relationship.
I have homes and I have services. One home can have a lot of services and one service can have a lot of homes. Everything is ok and I understand the way many to many works with the doctrine, i persisted all values before flush in my controller, but i always get this message:
An exception occurred while executing 'INSERT INTO homess_services (home_id, service_id) VALUES (?, ?)' with params [25, 7]:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '25' for key 'home_id'
My codes are (home entity):
<?php
namespace Filip\SymfonyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Filip\SymfonyBundle\FilipSymfonyBundle;
/**
* Home
*
* #ORM\Table(name="homes")
* #ORM\Entity
*
*
*/
class Home
{
/**
* #var ArrayCollection
*
* #ORM\ManyToMany(targetEntity="Service", inversedBy="homes")
* #ORM\JoinTable(name="homess_services")
*/
protected $services;
public function __construct() {
$this->photos = new ArrayCollection();
$this->services = new ArrayCollection();
}
/**
* Renders a publication as a string
*
* #return string
*/
public function __toString (){
return $this->getName();
}
/**
* Add services
*
* #param \Filip\SymfonyBundle\Entity\Service $services
* #return Home
*/
public function addService(\Filip\SymfonyBundle\Entity\Service $services)
{
$this->services[] = $services;
return $this;
}
/**
* Remove services
*
* #param \Filip\SymfonyBundle\Entity\Service $services
*/
public function removeService(\Filip\SymfonyBundle\Entity\Service $services)
{
$this->services->removeElement($services);
}
/**
* Get services
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getServices()
{
return $this->services;
}
Service entity:
<?php
namespace Filip\SymfonyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Filip\SymfonyBundle\FilipSymfonyBundle;
/**
* Service
*
* #ORM\Table("services")
* #ORM\Entity
*/
class Service
{
/**
* #var ArrayCollection
*
* #ORM\ManyToMany(targetEntity="Home", mappedBy="services")
*/
protected $homes;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM
\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="category", type="string", length=45)
*/
private $category;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=45)
*/
private $name;
/**
* Renders a service as a string
*
* #return string
*/
/**
* Get id
*
6
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set category
*
* #param string $category
* #return Service
*/
public function setCategory($category)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return string
*/
public function getCategory()
{
return $this->category;
}
/**
* Set name
*
* #param string $name
* #return Service
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
public function __construct()
{
$this->homes = new ArrayCollection();
}
/**
* Add homes
*
* #param \Filip\SymfonyBundle\Entity\Home $homes
* #return Service
*/
public function addHome(\Filip\SymfonyBundle\Entity\Home $homes)
{
$this->homes[] = $homes;
return $this;
}
/**
* Remove homes
*
* #param \Filip\SymfonyBundle\Entity\Home $homes
*/
public function removeHome(\Filip\SymfonyBundle\Entity\Home $homes)
{
$this->homes->removeElement($homes);
}
/**
* Get homes
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getHomes()
{
return $this->homes;
}
}
Form(HomeType):
<?php
namespace Filip\SymfonyBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class HomeType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('city')
->add('region')
->add('phone')
->add('address')
->add('email')
->add('website')
->add('content')
->add('youtubeApi')
->add('premium')
->add('services' , 'entity' , array(
'class' => 'FilipSymfonyBundle:Service' ,
'property' => 'name' ,
'expanded' => true ,
'multiple' => true ,
));
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Filip\SymfonyBundle\Entity\Home'
));
}
/**
* #return string
*/
public function getName()
{
return 'filip_symfonybundle_home';
}
}
Home controller:
/**
* Creates a new Home entity.
*
* #Route("/", name="home_create")
* #Method("POST")
* #Template("FilipSymfonyBundle:Home:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new Home();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$services = $entity->getServices();
foreach($services as $service) {
$entity->addService($service);
$em->persist($service);
}
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('home_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a form to create a Home entity.
*
* #param Home $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Home $entity)
{
$form = $this->createForm(new HomeType(), $entity, array(
'action' => $this->generateUrl('home_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
in the if($form->isValid()) part you don't need to call the addService() method in the foreach loop as Symfony will do this for you on the handleRequest() call.
If the Home entity is at the owning side of the ManyToMany relation you don't need to persist every Service object too. So you can try to remove the whole foreach loop too.

Symfony FOS Rest Bundle Api Call Many to Many Relationship

I seem to have an issue. And I'm sure it has a really simple fix. I have an API which uses FOS Rest bundle. I have a call which sends a POST request to postCreateTimesheetAction( Request $request ) which creates an empty row in the Timesheet Table. I have another call patchTimesheetAction which laters adds some data to the table. Okay all is well. I have another call patchCareoptionAction( Timesheet $timesheet ) which creates a row in a table which has a many to many relationship built from CareOptions.php(below) and Timesheet.php(below). All the api calls work good and function as they should. I will post them below here:
creates a blank new timesheet row in the Timesheet table: (Timesheet.php)
curl -H "Accept: application/json" -H "Content-type: application/json" -i -X POST -d '{"homecare_homecarebundle_timesheet":""}' www.hc-timesheets-demo.com/app_dev.php/api/v1/create/timesheet
updates the timesheet row with data:
curl -i -H "Accept: application/json" -H "Content-type: application/json" -d '{"homecare_homecarebundle_timesheet":{"agency":"157","recipient":"154","pca":"16","service":"6"}}' -X PATCH www.hc-timesheets-demo.com/app_dev.php/api/v1/timesheet/31
and finally creates the many to many relationship:
curl -i -H "Accept: application/json" -H "Content-type: application/json" -d '{"homecare_homecarebundle_timesheet":{"careOption":[456,457] }}' -X PATCH www.hc-timesheets-demo.com/app_dev.php/api/v1/careoption/31
notice the 31 at the end of the patch request. That is the id of the timesheet created in the table from the first api call. So lets get to my question! Whenever i call the 3rd api call i successfully create the many to many rows in the table. But when i call it again it does not replace the old rows with the new ones. It just adds more rows to the table. I want the many to many table rows to be updated and the old ones gone. Do i need to delete them out first? Let me explain a little more. If you see in the 3rd api call I'm adding 2 careOptions to the timesheet: (careOptions 456 and 457). Well if I call it again, and lets say I want to add 458 and 459. I want 456 and 457 to automatically delete and be gone. Please someone help me out??!!
Here is the owning side of the many to many relationship
<?php
//src/Homecare/HomecareBundle/Entity/CareOptions.php
namespace Homecare\HomecareBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* CareGoals
*
* #ORM\Table(name="careoptions")
* #ORM\Entity(repositoryClass="Homecare\HomecareBundle\Entity\Repository\CareOptionsRepository")
*/
class CareOptions
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity="CareOptionsTimesheets", mappedBy="careOption")
*/
private $care_options_timesheets;
/**
* #var string
*
* #ORM\Column(name="care_option", type="string", length=255)
*/
private $careOption;
/**
* #ORM\ManyToMany(targetEntity="CareGoals", mappedBy="careOption")
*/
private $careGoals;
/**
* #ORM\ManyToMany(targetEntity="Timesheet", inversedBy="careOption", cascade={"persist"})
*/
private $timesheet;
public function __construct()
{
$this->care_options_timesheets = new ArrayCollection();
$this->timesheet = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
//add a to string method so that the object can be displayed in the twig template
/*
public function __toString()
{
return $this->getCareGoal();
}
*/
/**
* Set careOption
*
* #param string $careOption
* #return CareOptions
*/
public function setCareOption($careOption)
{
$this->careOption = $careOption;
return $this;
}
/**
* Get careOption
*
* #return string
*/
public function getCareOption()
{
return $this->careOption;
}
/**
* Add care_options_timesheets
*
* #param \Homecare\HomecareBundle\Entity\CareOptions_Timesheets $careOptionsTimesheets
* #return CareOptions
*/
public function addCareOptionsTimesheet(\Homecare\HomecareBundle\Entity\CareOptionsTimesheets $careOptionsTimesheets)
{
$this->care_options_timesheets[] = $careOptionsTimesheets;
return $this;
}
/**
* Remove care_options_timesheets
*
* #param \Homecare\HomecareBundle\Entity\CareOptions_Timesheets $careOptionsTimesheets
*/
public function removeCareOptionsTimesheet(\Homecare\HomecareBundle\Entity\CareOptionsTimesheets $careOptionsTimesheets)
{
$this->care_options_timesheets->removeElement($careOptionsTimesheets);
}
/**
* Get care_options_timesheets
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCareOptionsTimesheets()
{
return $this->care_options_timesheets;
}
/**
* Add careGoals
*
* #param \Homecare\HomecareBundle\Entity\CareGoals $careGoals
* #return CareOptions
*/
public function addCareGoal(\Homecare\HomecareBundle\Entity\CareGoals $careGoals)
{
$this->careGoals[] = $careGoals;
return $this;
}
/**
* Remove careGoals
*
* #param \Homecare\HomecareBundle\Entity\CareGoals $careGoals
*/
public function removeCareGoal(\Homecare\HomecareBundle\Entity\CareGoals $careGoals)
{
$this->careGoals->removeElement($careGoals);
}
/**
* Get careGoals
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCareGoals()
{
return $this->careGoals;
}
public function __toString() {
return $this->getCareOption();
}
/**
* Add timesheet
*
* #param \Homecare\HomecareBundle\Entity\Timesheet $timesheet
* #return CareOptions
*/
public function addTimesheet(\Homecare\HomecareBundle\Entity\Timesheet $timesheet)
{
$this->timesheet[] = $timesheet;
return $this;
}
/**
* Remove timesheet
*
* #param \Homecare\HomecareBundle\Entity\Timesheet $timesheet
*/
public function removeTimesheet(\Homecare\HomecareBundle\Entity\Timesheet $timesheet)
{
$this->timesheet->removeElement($timesheet);
}
/**
* Get timesheet
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTimesheet()
{
return $this->timesheet;
}
}
Here is the other side of the many to many relationship:
<?php
//src/Homecare/HomecareBundle/Entity/Timesheet.php
namespace Homecare\HomecareBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation\Type;
use JMS\Serializer\Annotation\SerializedName;
/**
* Timesheet
*
* #ORM\Table(name="timesheet")
* #ORM\Entity(repositoryClass="Homecare\HomecareBundle\Entity\Repository\TimesheetRepository")
*/
class Timesheet
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #Type("integer")
* #SerializedName("id")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Agency", inversedBy="actualTimesheets")
* #ORM\JoinColumn(name="agency_id", referencedColumnName="id")
* #Type("Homecare\HomecareBundle\Entity\Agency")
* #SerializedName("agency")
*/
private $agency;
/**
* #ORM\ManyToOne(targetEntity="Recipient", inversedBy="actualTimesheets")
* #ORM\JoinColumn(name="recipient_id", referencedColumnName="id")
* #Type("Homecare\HomecareBundle\Entity\Recipient")
* #SerializedName("recipient")
*/
private $recipient;
/**
* #ORM\ManyToOne(targetEntity="Pca", inversedBy="actualTimesheets")
* #ORM\JoinColumn(name="pca_id", referencedColumnName="id")
* #Type("Homecare\HomecareBundle\Entity\Pca")
* #SerializedName("pca")
*/
private $pca;
/**
* #ORM\ManyToOne(targetEntity="Services", inversedBy="actualTimesheets")
* #ORM\JoinColumn(name="service_id", referencedColumnName="id")
* #Type("Homecare\HomecareBundle\Entity\Services")
* #SerializedName("service")
*/
private $service;
/**
* #ORM\Column(name="continueTimesheetNumber",type="integer",nullable=true)
* #Type("integer")
* #SerializedName("continueTimesheetNumber")
*/
private $continueTimesheetNumber;
/**
* #ORM\ManyToOne(targetEntity="VisitRatios", inversedBy="timesheets")
* #Type("Homecare\HomecareBundle\Entity\VisitRatios")
* #SerializedName("visitRatio")
*/
private $visitRatio;
/**
* #ORM\ManyToOne(targetEntity="TimeIn", inversedBy="timesheets")
* #Type("Homecare\HomecareBundle\Entity\TimeIn")
* #SerializedName("timeIn")
*/
private $timeIn;
/**
* #ORM\ManyToOne(targetEntity="TimeOut", inversedBy="timesheets")
* #Type("Homecare\HomecareBundle\Entity\TimeOut")
* #SerializedName("timeOut")
*/
private $timeOut;
/**
* #ORM\ManyToOne(targetEntity="Files", inversedBy="timesheets")
* #Type("Homecare\HomecareBundle\Entity\Files")
* #SerializedName("file")
*/
private $file;
/**
* #ORM\ManyToMany(targetEntity="CareOptions", mappedBy="timesheet", cascade={"persist"})
* #Type("Homecare\HomecareBundle\Entity\CareOptions")
* #SerializedName("careOption")
*/
private $careOption;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set agency
*
* #param \Homecare\HomecareBundle\Entity\Agency $agency
* #return Timesheet
*/
public function setAgency(\Homecare\HomecareBundle\Entity\Agency $agency = null)
{
$this->agency = $agency;
return $this;
}
/**
* Get agency
*
* #return \Homecare\HomecareBundle\Entity\Agency
*/
public function getAgency()
{
return $this->agency;
}
/**
* Set recipient
*
* #param \Homecare\HomecareBundle\Entity\Recipient $recipient
* #return Timesheet
*/
public function setRecipient(\Homecare\HomecareBundle\Entity\Recipient $recipient = null)
{
$this->recipient = $recipient;
return $this;
}
/**
* Get recipient
*
* #return \Homecare\HomecareBundle\Entity\Recipient
*/
public function getRecipient()
{
return $this->recipient;
}
/**
* Set pca
*
* #param \Homecare\HomecareBundle\Entity\Pca $pca
* #return Timesheet
*/
public function setPca(\Homecare\HomecareBundle\Entity\Pca $pca = null)
{
$this->pca = $pca;
return $this;
}
/**
* Get pca
*
* #return \Homecare\HomecareBundle\Entity\Pca
*/
public function getPca()
{
return $this->pca;
}
/**
* Set service
*
* #param \Homecare\HomecareBundle\Entity\Services $service
* #return Timesheet
*/
public function setService(\Homecare\HomecareBundle\Entity\Services $service = null)
{
$this->service = $service;
return $this;
}
/**
* Get service
*
* #return \Homecare\HomecareBundle\Entity\Services
*/
public function getService()
{
return $this->service;
}
/**
* Set continueTimesheetNumber
*
* #param integer $continueTimesheetNumber
* #return Timesheet
*/
public function setContinueTimesheetNumber($continueTimesheetNumber)
{
$this->continueTimesheetNumber = $continueTimesheetNumber;
return $this;
}
/**
* Get continueTimesheetNumber
*
* #return integer
*/
public function getContinueTimesheetNumber()
{
return $this->continueTimesheetNumber;
}
/**
* Set visitRatio
*
* #param \Homecare\HomecareBundle\Entity\VisitRatios $visitRatio
* #return Timesheet
*/
public function setVisitRatio(\Homecare\HomecareBundle\Entity\VisitRatios $visitRatio = null)
{
$this->visitRatio = $visitRatio;
return $this;
}
/**
* Get visitRatio
*
* #return \Homecare\HomecareBundle\Entity\VisitRatios
*/
public function getVisitRatio()
{
return $this->visitRatio;
}
/**
* Set timeIn
*
* #param \Homecare\HomecareBundle\Entity\TimeIn $timeIn
* #return Timesheet
*/
public function setTimeIn(\Homecare\HomecareBundle\Entity\TimeIn $timeIn = null)
{
$this->timeIn = $timeIn;
return $this;
}
/**
* Get timeIn
*
* #return \Homecare\HomecareBundle\Entity\TimeIn
*/
public function getTimeIn()
{
return $this->timeIn;
}
/**
* Set timeOut
*
* #param \Homecare\HomecareBundle\Entity\TimeOut $timeOut
* #return Timesheet
*/
public function setTimeOut(\Homecare\HomecareBundle\Entity\TimeOut $timeOut = null)
{
$this->timeOut = $timeOut;
return $this;
}
/**
* Get timeOut
*
* #return \Homecare\HomecareBundle\Entity\TimeOut
*/
public function getTimeOut()
{
return $this->timeOut;
}
/**
* Set file
*
* #param \Homecare\HomecareBundle\Entity\Files $file
* #return Timesheet
*/
public function setFile(\Homecare\HomecareBundle\Entity\Files $file = null)
{
$this->file = $file;
return $this;
}
/**
* Get file
*
* #return \Homecare\HomecareBundle\Entity\Files
*/
public function getFile()
{
return $this->file;
}
/**
* Constructor
*/
public function __construct()
{
$this->careOption = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add careOption
*
* #param \Homecare\HomecareBundle\Entity\CareOptions $careOption
* #return Timesheet
*/
public function addCareOption(\Homecare\HomecareBundle\Entity\CareOptions $careOption)
{
$careOption->addTimesheet( $this );
$this->careOption[] = $careOption;
return $this;
}
/**
* Remove careOption
*
* #param \Homecare\HomecareBundle\Entity\CareOptions $careOption
*/
public function removeCareOption(\Homecare\HomecareBundle\Entity\CareOptions $careOption)
{
$this->careOption->removeElement($careOption);
}
/**
* Get careOption
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCareOption()
{
return $this->careOption;
}
}
Here is the formBuilder TimesheetType.php
<?php
//src/Homecare/HomecareBundle/Form/TimesheetType.php
namespace Homecare\HomecareBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class TimesheetType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('agency')
->add('recipient')
->add('pca')
->add('service')
->add('continueTimesheetNumber')
->add('visitRatio')
->add('timeIn')
->add('timeOut')
;
$builder->add('careOption', 'entity', array(
'class' => 'HomecareHomecareBundle:CareOptions',
'property' => 'careOption',
'expanded' => true,
'multiple' => true,
'label' => false,
'by_reference' => false,
));
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Homecare\HomecareBundle\Entity\Timesheet',
'csrf_protection' => false,
));
}
/**
* #return string
*/
public function getName()
{
return 'homecare_homecarebundle_timesheet';
}
}
Here are the ApiControllers:
<?php
//src/Homecare/HomecareApiBundle/Controller/TimesheetApiController.php
namespace Homecare\HomecareApiBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\Controller\Annotations\View;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Homecare\HomecareBundle\Entity\Timesheet;
use Homecare\HomecareBundle\Entity\Services;
use Homecare\HomecareBundle\Entity\CareOptions;
use Homecare\HomecareBundle\Form\TimesheetType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use JMS\Serializer\SerializerBuilder;
use FOS\RestBundle\View\View as V;
use Doctrine\Common\Collections\ArrayCollection;
class TimesheetApiController extends Controller
{
/**
* #View()
*/
public function patchCareoptionAction( Timesheet $timesheet )
{
return $this->updateTimesheetForm( $timesheet );
}
/**
* #View()
*/
public function postCreateTimesheetAction( Request $request )
{
return $this->createTimesheetForm( $request, new Timesheet() );
}
/**
* #View()
*/
public function patchTimesheetAction( Timesheet $timesheet )
{
return $this->updateTimesheetForm( $timesheet );
}
private function setMethod( $statusCode, $timesheet = null ){
switch( $statusCode ) {
case 201:
return array( 'method' => 'POST' );
break;
case 204:
return array(
'action' => $this->generateUrl('patch_timesheet', array('timesheet' => $timesheet->getId())),
'method' => 'PATCH'
);
break;
}
}
/**
* #View()
*/
private function updateTimesheetForm( Timesheet $timesheet)
{
$statusCode = 204;
$form = $this->createForm(new TimesheetType(), $timesheet, $this->setMethod( $statusCode, $timesheet ) );
$form->handleRequest( $this->getRequest() );
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
//$careOption = $em->getRepository( "HomecareHomecareBundle:CareOptions" )->findOneById(456);
//$timesheet->addCareOption( $careOption );
$em->persist( $timesheet );
$em->flush();
$response = new Response();
$response->setStatusCode( $statusCode );
return $response;
}
return V::create($form, 400);
}
/**
* #View()
*/
private function createTimesheetForm( $request, Timesheet $timesheet )
{
$statusCode = 201;
$form = $this->createForm( new TimesheetType(), $timesheet, $this->setMethod( $statusCode ) );
$form->handleRequest( $this->getRequest() );
if ( $form->isValid() ) {
//$user->save();
//$timesheet = $form->getData();
$response = new Response();
$response->setStatusCode(201);
$em = $this->getDoctrine()->getManager();
$em->persist( $timesheet );
$em->flush();
//return V::create($form, 201);
//return $response;
//return array( $form, array("timesheet" => array("id" => $timesheet->getId() ) ) );
return V::create( array("createdTimesheet" => array("id" => $timesheet->getId() ) ), $statusCode );
// return array( $form, array("timesheet" => array("id" => $timesheet->getId() ) ) );
}
return V::create($form, 400);
}
}
You need to either call a second API to delete the 2 previous added options, or in your updateTimesheet you delete the 2 previous added options, you can select them by a query by creating a function in your Repository :
public function getLastTwoCareOptions(){
$query = "SELECT co.id FROM CareOptionTable co INNER JOIN TimesheetTable ts WHERE ts.id = timesheetid ORDER BY co.id LIMIT 2;";
$connection = $this->getEntityManager()->getConnection();
$prep_query = $connection->prepare($req);
$result = $prep_query->fetchAll();
}
You can make the limit as parameter to the function if you may need to update 3 last care options someday or more.
Then you get the ids and remove them from the timesheet.
Another solution is to use the same query differently to delete them with SQL query without having to select and then delete.

Categories