Laravel 5.2 belongstoMany in views - php

I'm trying to make a belongstoMany relationship in Laravel 5.2.39 between people and places but am unable to pass the information into a view in a select box. I just get: "Error Exception: Undefined variable: people". It also is not saving and making the pivot table entries.
I have created the pivot table person_place with 'place_id' and 'person_id' columns which correspond to the 'people' and 'places' table.
App/Person.php (Person Model)
<?php
namespace ss;
use ss\Place;
use Illuminate\Database\Eloquent\Model;
class Person extends Model
{
/**
* Fillable fields
*
* #var array
*/
protected $fillable = [
'name',
'type',
'status',
'notes',
'email',
'phone',
'alt',
'web',
'first',
'last',
'title',
];
public function places()
{
return $this->belongsToMany('Place');
}
}
App/Place.php (Place Model)
<?php
namespace ss;
use ss\Person;
use Illuminate\Database\Eloquent\Model;
class Place extends Model
{
/**
* Fillable fields
*
* #var array
*/
protected $fillable = [
'name',
'type',
'status',
'notes',
'email',
'phone',
'alt',
'web',
'address1',
'address2',
'city',
'state',
'zip',
'country',
];
public function people()
{
return $this->belongsToMany('Person');
}
}
App/Http/Controllers/PlaceController.php (Places Controller)
<?php namespace ss\Http\Controllers;
use ss\Place;
use ss\Person;
use ss\Http\Requests;
use Illuminate\Http\Request;
use View;
use Session;
class PlaceController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$places = Place::all();
$people = Person::pluck('name','id')->all();
return View::make('places.index', compact('places','people'));
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
$people = Person::lists('last', 'id');
return view('places.create', compact('people'));
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required'
]);
$input = $request->all();
Place::create($input);
Session::flash('flash_message', 'Place successfully added!');
return redirect()->action('PlaceController#index');
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
$place = Place::findOrFail($id);
return view('places.show')->withPlace($place);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
$place = Place::findOrFail($id);
$people = Person::pluck('name','id')->all();
return view('places.edit', compact('place','people'));
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id, Request $request)
{
$this->validate($request, [
'name' => 'required'
]);
$input = $request->except('people');
$place = Place::findOrFail($id);
$peopleIDs = $this->place->people($peopleIds);
$place->fill($input)->save();
Session::flash('flash_message', 'Place successfully edited!');
return redirect()->action('PlaceController#index', $place);
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
$place = Place::findOrFail($id);
$place->delete();
Session::flash('flash_message', 'Place successfully deleted!');
return redirect()->action('PlaceController#index');
}
}
resources/views/places/edit.blade.index.php (Places View, where I'm trying to build select list -not working)
#section('aside')
{!! Form::select('people', $people, null, ['class' => '', 'multiple']) !!}
<ul class="section table-of-contents">
<li>New Time</li>
<li>New Money</li>
<li> </li>
<li>New Sub-Task</li>
</ul>
#endsection
resources/views/places/create.blade.index.php (Places View with a select list that works but does not make a pivot table when saving)
#section('aside')
{!! Form::select('people', $people, null, ['class' => '', 'multiple']) !!}
#endsection
Have tried various methods of "with" and "attach" and am unable to get a result. Interestingly, even if I specifically place "$person = "foo"; in my edit method it still says it is undefined.
Thank you for your help.
EDIT: Updated Code

In the PlacesController, your edit($id) method does not pass an array of people to the view.
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
$place = Place::findOrFail($id);
$people = People::pluck('name','id')->all();
return view('places.edit', compact('place', 'people');
}

Related

New blogs not being shown or stored in the database

Once I delete a blog, it is deleted completely. I can make a new one, but it does not show on the website or in the database. This is my BlogController:
<?php
namespace App\Http\Controllers;
use App\Models\Blog;
use Illuminate\Http\Request;
class BlogController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$blog = Blog::paginate(5);
return view('blogs.index', compact('blog'))
->with('i',(request()->input('page',1)-1)*5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('blogs.create');
Blog::create($request->all());
return redirect()->route('blogs.index')
->with('success','Blog created successfully.');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'description' => 'required',
]);
$blog = new Blog;
$blog->title = $request->title;
$blog->description = $request->description;
$blog->save();
return redirect()->route('blogs.index');
}
/**
* Display the specified resource.
*
* #param \App\Blog $blog
* #return \Illuminate\Http\Response
*/
public function show(Blog $blog)
{
return view('blogs.show', compact('blog'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Blog $blog
* #return \Illuminate\Http\Response
*/
public function edit(Blog $blog)
{
return view('blogs.edit', compact('blog'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Blog $blog
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Blog $blog)
{
$request->validate([
'title' => 'required',
'description' => 'required',
]);
// $blog->title = $request->title;
// $blog->description = $request->description;
$blog->fill($request);
// dd($blog);
return redirect()->route('blogs.index')
->with('success','Blog updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Blog $blog
* #return \Illuminate\Http\Response
*/
public function destroy(Blog $blog)
{
$blog->delete();
return redirect()->route('blogs.index')
->with('success','Blog deleted successfully');
}
}
And the problem is apparently the 103th line, public function update: $blog->fill($request); It does not store in the database nor is it visible on the webpage/blog. I tried deleting that specific line, but it is the same. Nothing changes. I do not understand what the issue could be. Can someone help?
1ST OPTION In order for the fill method to work, you must call $blog->save() after that.
$blog->fill($request);
$blog->save();
Also when you use fill method you are mass assigning values. By default Laravel protects you from mass assigning fields.
Open your Blog.php model and add the fields you want to mass assign to the array $fillable
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'title',
'description',
];
2ND OPTION is to use the update method (don't forget to also add fields in $fillable in the model from 1st option since update method is also mass assigning fields):
$blog->update($request);
3RD OPTION manually assign each field one-by-one just like you did in the store method:
$blog->title = $request->title;
$blog->description = $request->description;
$blog->save();
The fill function dose not update data in database.
This function only assignment value to attribute in protected $fillable = ['title','description']; in Blog model.
Using update function to update data to database.
$blog->fill($request);
$blog->update();

Laravel image save as .tmp in the db even though the file uploaded in the correct folder

I'm trying to add a user to the database in Laravel.
following is my User Model.
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable implements MustVerifyEmail {
use HasFactory, Notifiable, HasRoles;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'image_id',
'country_id',
'email',
'password',
'gender',
'date_of_birth',
'region_id',
'role_id',
'is_email_verified'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
And this is my User Controller.
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use Spatie\Permission\Models\Role;
use DB;
use Hash;
class UserController extends Controller {
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request) {
$data = User::orderBy('id','DESC')->paginate(5);
return view('admins.users.index',compact('data'))
->with('i', ($request->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create() {
$roles = Role::pluck('name','name')->all();
return view('admins.users.create',compact('roles'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request) {
$data = $request->input('roles');
foreach($data as $key => $value) {
$key = 'data' . $key;
$$key = $value;
}
$roleid=$data0;
if($roleid=='Admin') {
$roleid='1';
} else if($roleid=='Regional Admin') {
$roleid='2';
} else {
$roleid='3';
}
$request->merge(['role_id' => ''.$roleid.'']);
$request->merge(['gender' => 'M']);
$request->merge(['date_of_birth' => '1992-01-11']);
$this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|same:confirm-password',
'roles' => 'required',
'image_id' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'role_id'=>'required',
'gender'=>'required',
'date_of_birth'=>'required'
]);
if ($image = $request->file('image_id')) {
$destinationPath = 'propics/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image_id'] = $profileImage;
$request->merge(['image_id' => $profileImage]);
}
//$input['role_id']=$request->input('roles');
dd($request->all());
$input = $request->all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
$user->assignRole($request->input('roles'));
return redirect()->route('users.index')
->with('success','User created successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id) {
$user = User::find($id);
return view('admins.users.show',compact('user'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id) {
$user = User::find($id);
$roles = Role::pluck('name','name')->all();
$userRole = $user->roles->pluck('name','name')->all();
return view('admins.users.edit',compact('user','roles','userRole'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id) {
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email,'.$id,
'password' => 'same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
if(!empty($input['password'])) {
$input['password'] = Hash::make($input['password']);
} else {
$input = array_except($input,array('password'));
}
$user = User::find($id);
$user->update($input);
DB::table('model_has_roles')->where('model_id',$id)->delete();
$user->assignRole($request->input('roles'));
return redirect()->route('admins.users.index')
->with('success','User updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id) {
User::find($id)->delete();
return redirect()->route('admins.users.index')
->with('success','User deleted successfully');
}
}
Now my question is that this stores my users in the DB perfectly but the user image stores as .tmp.
The file also get uploaded into the correct folder, but when it stores in the DB it stores as,
C:\xampp\tmp\phpA031.tmp
instead of .png or .jpg
Where should I correct my code?
public function store(Request $request){
$post = new Post([
'title'=>$request->get('title'),
'description'=>$request->get('description')
]);
$imageName = $request->title.'.png';
$request->image->move(public_path('images/posts'),$imageName);
$post->save();
return redirect()->back();
}
now you create view and create 3 input fields: name title (text), description (textarea) and image (file)

Notifications for comments not working in laravel

error
enter image description here
I am trying to send notifications of the event when some likes and comment on his post, notifications for comments and likes working
here is my notification class.
i have error in my CommentController if ($event->user_id != $comment->user_id)
class NewCommentEvent extends Notification
{
use Queueable;
protected $comment;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($comment)
{
$this->comment = $comment;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['database'];
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toDatabase($notifiable)
{
return [
'comment' => $this->comment,
'event' => Event::find($this->comment->event_id),
'user' => User::find($this->comment->user_id)
];
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
My controller function code for notifications on comments
public function store(CommentRequest $request)
{
$event = Event::findOrFail($request->event_id);
Comment::create([
'comment' => $request->comment,
'user_id' => Auth::id(),
'event_id' => $event->id
]);
if ($event->user_id != $comment->user_id) {
$user = User::find($event->user_id);
$user->notify(new NewCommentEvent($comment));
}
Toastr::success('Comment post with success','', ["positionClass" => "toast-top-center"]);
return redirect()->back();
}
my CommenRequest
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
class CommentRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return Auth::check();
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'comment' => 'required|max:2000',
];
}
}
In your controller: the variable $comment is not defined.
From Laravel docs:
The create method returns the saved model instance.
so the solution is:
$comment = Comment::create([
'comment' => $request->comment,
'user_id' => Auth::id(),
'event_id' => $event->id
]);
you have not defined your $comment, you just created a comment. This is throwing the error
$comment = Comment::create([
.
.
]);
This will fix your issue
The error message was clear. $comment is undefined. Replace your controller code with the follow:
public function store(CommentRequest $request)
{
$event = Event::findOrFail($request->event_id);
// defined comment here
$comment = Comment::create([
'comment' => $request->comment,
'user_id' => Auth::id(),
'event_id' => $event->id
]);
if ($event->user_id != $comment->user_id) {
$user = User::find($event->user_id);
$user->notify(new NewCommentEvent($comment));
}
Toastr::success('Comment post with success','', ["positionClass" => "toast-top-center"]);
return redirect()->back();
}

Laravel Roles without pivot table

I am student and i am new with Laravel and i have this UserController which used to assign multi Roles to User (using pivot table user_role) but i want to assign one role to each user (without pivot table) so i added role_id foreign in table user but i dont know what to change in UserController file.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\Role;
use DB;
use Hash;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$data = User::orderBy('id','DESC')->paginate(5);
return view('users.index',compact('data'))
->with('i', ($request->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$roles = Role::pluck('display_name','id');
return view('users.create',compact('roles'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
foreach ($request->input('roles') as $key => $value) {
$user->attachRole($value);
}
return redirect()->route('users.index')
->with('success','User created successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$user = User::find($id);
return view('users.show',compact('user'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$user = User::find($id);
$roles = Role::pluck('display_name','id');
$userRole = $user->roles->pluck('id','id')->toArray();
return view('users.edit',compact('user','roles','userRole'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email,'.$id,
'password' => 'same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
if(!empty($input['password'])){
$input['password'] = Hash::make($input['password']);
}else{
$input = array_except($input,array('password'));
}
$user = User::find($id);
$user->update($input);
DB::table('role_user')->where('user_id',$id)->delete();
foreach ($request->input('roles') as $key => $value) {
$user->attachRole($value);
}
return redirect()->route('users.index')
->with('success','User updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
User::find($id)->delete();
return redirect()->route('users.index')
->with('success','User deleted successfully');
}
}
and you can find all the code here:
http://itsolutionstuff.com/post/laravel-52-user-acl-roles-and-permissions-with-middleware-using-entrust-from-scratch-tutorialexample.html
this mean so much to me if you help me and thanks.

HOW TO DISPLAY DATA IN DROP DOWN LIST FROM OTHER TABLE IN CAKEPHP 3?

I have two tables:
departamento (spanish of "region")
provincia (spanish of "province")
"departamento" have three fields:
id_departamento departamento (name of region) presidente (governor)
"provincia" have four fields:
id_provincia id_departamento (foreign key) provincia (name of province) gobernador (governor)
I generate cakephp code with command lines (models, controllers and templates).
but, in the generated view, show insert input id, and i don't want it -->
SCREEN CAPTURE
When i'm going to add a new province, i would like to display and replace the region id field by the name of region like drop down list
PROVINCIACONTROLLER.PHP
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* Provincia Controller
*
* #property \App\Model\Table\ProvinciaTable $Provincia
*/
class ProvinciaController extends AppController
{
/**
* Index method
*
* #return \Cake\Network\Response|null
*/
public function index()
{
$provincia = $this->paginate($this->Provincia);
$this->set(compact('provincia'));
$this->set('_serialize', ['provincia']);
}
/**
* View method
*
* #param string|null $id Provincium id.
* #return \Cake\Network\Response|null
* #throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$provincium = $this->Provincia->get($id, [
'contain' => []
]);
$this->set('provincium', $provincium);
$this->set('_serialize', ['provincium']);
}
/**
* Add method
*
* #return \Cake\Network\Response|void Redirects on successful add, renders view otherwise.
*/
public function add()
{
$provincium = $this->Provincia->newEntity();
if ($this->request->is('post')) {
$provincium = $this->Provincia->patchEntity($provincium, $this->request->data);
if ($this->Provincia->save($provincium)) {
$this->Flash->success(__('The provincium has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The provincium could not be saved. Please, try again.'));
}
}
$this->set(compact('provincium'));
$this->set('_serialize', ['provincium']);
}
/**
* Edit method
*
* #param string|null $id Provincium id.
* #return \Cake\Network\Response|void Redirects on successful edit, renders view otherwise.
* #throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function edit($id = null)
{
$provincium = $this->Provincia->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$provincium = $this->Provincia->patchEntity($provincium, $this->request->data);
if ($this->Provincia->save($provincium)) {
$this->Flash->success(__('The provincium has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The provincium could not be saved. Please, try again.'));
}
}
$this->set(compact('provincium'));
$this->set('_serialize', ['provincium']);
}
/**
* Delete method
*
* #param string|null $id Provincium id.
* #return \Cake\Network\Response|null Redirects to index.
* #throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$provincium = $this->Provincia->get($id);
if ($this->Provincia->delete($provincium)) {
$this->Flash->success(__('The provincium has been deleted.'));
} else {
$this->Flash->error(__('The provincium could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}
PROVINCIATABLE.PHP
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
/**
* Provincia Model
*
* #method \App\Model\Entity\Provincium get($primaryKey, $options = [])
* #method \App\Model\Entity\Provincium newEntity($data = null, array $options = [])
* #method \App\Model\Entity\Provincium[] newEntities(array $data, array $options = [])
* #method \App\Model\Entity\Provincium|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
* #method \App\Model\Entity\Provincium patchEntity(\Cake\Datasource\EntityInterface $entity, array $data,
array $options = [])
* #method \App\Model\Entity\Provincium[] patchEntities($entities, array $data, array $options = [])
* #method \App\Model\Entity\Provincium findOrCreate($search, callable $callback = null)
*/
class ProvinciaTable extends Table
{
/**
* Initialize method
*
* #param array $config The configuration for the Table.
* #return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->table('provincia');
$this->displayField('id_provincia');
$this->primaryKey('id_provincia');
}
/**
* Default validation rules.
*
* #param \Cake\Validation\Validator $validator Validator instance.
* #return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->integer('id_provincia')
->allowEmpty('id_provincia', 'create')
->add('id_provincia', 'unique', ['rule' => 'validateUnique', 'provider' => 'table']);
$validator
->integer('id_departamento')
->requirePresence('id_departamento', 'create')
->notEmpty('id_departamento');
$validator
->requirePresence('provincia', 'create')
->notEmpty('provincia');
$validator
->requirePresence('gobernador', 'create')
->notEmpty('gobernador');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* #param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* #return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->isUnique(['id_provincia']));
return $rules;
}
}
PROVINCIA.PHP
<?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
/**
* Provincium Entity
*
* #property int $id_provincia
* #property int $id_departamento
* #property string $provincia
* #property string $gobernador
*/
class Provincium extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* Note that when '*' is set to true, this allows all unspecified fields to
* be mass assigned. For security purposes, it is advised to set '*' to false
* (or remove it), and explicitly make individual fields accessible as needed.
*
* #var array
*/
protected $_accessible = [
'*' => true,
'id_provincia' => false
];
}
ADD.CTP (ADD PROVINCE)
<nav class="large-3 medium-4 columns" id="actions-sidebar">
<ul class="side-nav">
<li class="heading"><?= __('Actions') ?></li>
<li><?= $this->Html->link(__('List Provincia'), ['action' => 'index']) ?></li>
</ul>
</nav>
<div class="provincia form large-9 medium-8 columns content">
<?= $this->Form->create($provincium) ?>
<fieldset>
<legend><?= __('Add Provincium') ?></legend>
<?php
echo $this->Form->input('id_departamento');
echo $this->Form->input('provincia');
echo $this->Form->input('gobernador');
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
THANKS FOR YOUR HELP
If you want a drop down list of departmento, you need to fetch them using find('list') and set it to the template.
Considering your table name is Departmento, and you want to populate value id_departamento and text departamento, try the following:
/* Controller Code */
public function add()
{
$provincium = $this->Provincia->newEntity();
if ($this->request->is('post')) {
/* Other code */
}
/* Modified code starts */
$departmento = $this->Departmento->find('list', [
'keyField' => 'id_departamento',
'valueField' => 'departmento'
]);
$this->set(compact('departmento'));
/* Modified code ends*/
$this->set(compact('provincium'));
$this->set('_serialize', ['provincium']);
}
/* Template code */
echo $this->Form->select('id_departamento', $departmento, [
'empty' => 'Departmento'
]);

Categories