When I load the page, it gives me an error and tells me to reload.
However, when I add data to the database it works properly.
So, basically my list function isn't working and I don't know why.
I checked for typos, it can't be something like updating, because of all my other CRUD's work fine with the same method.
Controller :
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Requests\ProjectRequest;
use Backpack\CRUD\app\Http\Controllers\CrudController;
use Backpack\CRUD\app\Library\CrudPanel\CrudPanelFacade as CRUD;
/**
* Class ProjectCrudController
* #package App\Http\Controllers\Admin
* #property-read \Backpack\CRUD\app\Library\CrudPanel\CrudPanel $crud
*/
class ProjectCrudController extends CrudController
{
use \Backpack\CRUD\app\Http\Controllers\Operations\ListOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\ShowOperation;
public function setup()
{
$this->crud->setModel('App\Models\Project');
$this->crud->setRoute(config('backpack.base.route_prefix') . '/project');
$this->crud->setEntityNameStrings('project', 'projects');
}
protected function setupListOperation()
{
$this->crud->setColumns([
'name' => 'status',
'type' => 'text',
'label' => 'Status'
]);
$this->crud->setColumns([
'name' => 'topic',
'type' => 'text',
'label' => 'Topic'
]);
$this->crud->setColumns([
'name' => 'leader',
'type' => 'text',
'label' => 'Leader'
]);
$this->crud->setColumns([
'name' => 'email',
'type' => 'text',
'label' => 'Name'
]);
$this->crud->setColumns([
'name' => 'tags',
'type' => 'text',
'label' => 'Tags'
]);
}
protected function setupCreateOperation()
{
$this->crud->setValidation(ProjectRequest::class);
$this->crud->addField([
'name' => 'status',
'type' => 'text',
'label' => 'Status'
]);
$this->crud->addField([
'name' => 'topic',
'type' => 'text',
'label' => 'Topic'
]);
$this->crud->addField([
'name' => 'leader',
'type' => 'text',
'label' => 'Leader'
]);
$this->crud->addField([
'name' => 'email',
'type' => 'text',
'label' => 'Name'
]);
$this->crud->addField([
'name' => 'tags',
'type' => 'text',
'label' => 'Tags'
]);
}
protected function setupUpdateOperation()
{
$this->setupCreateOperation();
}
public function store()
{
$this->crud->hasAccessOrFail('create');
// execute the FormRequest authorization and validation, if one is required
$request = $this->crud->validateRequest();
// insert item in the db
$item = $this->crud->create($this->crud->getStrippedSaveRequest());
$this->data['entry'] = $this->crud->entry = $item;
// show a success message
\Alert::success(trans('backpack::crud.insert_success'))->flash();
// save the redirect choice for next time
$this->crud->setSaveAction();
return $this->crud->performSaveAction($item->getKey());
}
}
Model:
<?php
namespace App\Models;
use Backpack\CRUD\app\Models\Traits\CrudTrait;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
use CrudTrait;
/*
|--------------------------------------------------------------------------
| GLOBAL VARIABLES
|--------------------------------------------------------------------------
*/
protected $table = 'projects';
// protected $primaryKey = 'id';
// public $timestamps = false;
protected $guarded = ['project_id'];
protected $fillable = ['topic', 'status', 'leader', 'email', 'tags'];
// protected $fillable = [];
// protected $hidden = [];
// protected $dates = [];
/*
|--------------------------------------------------------------------------
| FUNCTIONS
|--------------------------------------------------------------------------
*/
/*
|--------------------------------------------------------------------------
| RELATIONS
|--------------------------------------------------------------------------
*/
/*
|--------------------------------------------------------------------------
| SCOPES
|--------------------------------------------------------------------------
*/
/*
|--------------------------------------------------------------------------
| ACCESSORS
|--------------------------------------------------------------------------
*/
/*
|--------------------------------------------------------------------------
| MUTATORS
|--------------------------------------------------------------------------
*/
}
Request:
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use Illuminate\Foundation\Http\FormRequest;
class ProjectRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
// only allow updates if the user is logged in
return backpack_auth()->check();
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'topic' => 'required|min:5|max:255',
'status' => '',
'leader' => 'required|min:5|max:255',
'email' => 'required|min:5|max:255',
'tags' => 'required|min:5|max:255'
];
}
/**
* Get the validation attributes that apply to the request.
*
* #return array
*/
public function attributes()
{
return [
//
];
}
/**
* Get the validation messages that apply to the request.
*
* #return array
*/
public function messages()
{
return [
//
];
}
}
protected $primaryKey = 'project_id';
Database had project_id instead of just id, so this should work.
Related
i want to use sub fillable array in model
protected $fillable = [
'requestInfo'=>[
'companyname',
'province',
'district',
'village',
'phone',
],
'owner'=>[
'fullname',
'province',
'district',
'village',
'nationality',
'fax',
'phone',
'factorynamela',
'factorynameen',
'located',
'locatprovince',
'locatdistrict',
'locatvillage',
'locatein'
],
];
but have error:
C:\xampp\htdocs\mocbizrrequest\blog\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\GuardsAttributes.php
/**
* Determine if the model is totally guarded.
*
* #return bool
*/
public function totallyGuarded()
{
return count($this->getFillable()) == 0 && $this->getGuarded() == ['*'];
}
/**
* Get the fillable attributes of a given array.
*
* #param array $attributes
* #return array
*/
protected function fillableFromArray(array $attributes)
{
if (count($this->getFillable()) > 0 && ! static::$unguarded) {
return array_intersect_key($attributes, array_flip($this->getFillable()));
}
return $attributes;
}
}
Arguments
"array_flip(): Can only flip STRING and INTEGER values!"
ErrorException (E_WARNING)
array_flip(): Can only flip STRING and INTEGER values!
please help me thank
i want to use sub fillable array in model
in my model file
<?php
/**
* Created by IntelliJ IDEA.
* User: EXTRA
* Date: 4/5/2019
* Time: 11:48 AM
*/
namespace App\Model;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class RequestFrom extends Eloquent
{
protected $connection = 'mongodb';
protected $collection = 'requestForm';
protected $fillable = [
'requestInfo'=>[
'companyname',
'province',
'district',
'village',
'phone',
],
'owner'=>[
'fullname',
'province',
'district',
'village',
'nationality',
'fax',
'phone',
'factorynamela',
'factorynameen',
'located',
'locatprovince',
'locatdistrict',
'locatvillage',
'locatein'
],
];
in controller file
namespace App\Http\Controllers;
use App\Model\RequestFrom;
use Illuminate\Http\Request;
class RequestFromController extends Controller
{
public function index()
{
$requestForms = RequestFrom::all();
return view('requestForm.index',compact('requestForms'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
public function create()
{
return view('requestForm.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
request()->validate([
'requestInfo'=>[
'companyname' => 'required',
'province' => 'required',
'district' => 'required',
'village' => 'required',
'phone' => 'required'
],
'owner'=>[
'fullname' => 'required',
'province' => 'required',
'district' => 'required',
'village' => 'required',
'nationality' => 'required',
'fax' => 'required',
'phone' => 'required',
'factorynamela' => 'required',
'factorynameen' => 'required',
'located' => 'required',
'locatprovince' => 'required',
'locatdistrict' => 'required',
'locatvillage' => 'required',
'locatein' => 'required'
],
]);
RequestFrom::create($request->all());
return redirect()->route('requestForm.index')
->with('success','created successfully.');
}
I have a database having relationship of three levels. cheque->account->customer. Now I am trying to retrieve data from all three table at same time using the following method.
$query = Cheque::find();
$query->joinWith(['account.customer']);
$query->orderBy('sr desc');
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
Cheque Model:
class Cheque extends \common\components\db\ActiveRecord {
/**
* #inheritdoc
*/
public static function tableName() {
return 'cheque';
}
/**
* #inheritdoc
*/
public function rules() {
return [
[['sr'], 'integer'],
[['ID', 'account_ID'], 'required'],
[['ID', 'account_ID', 'created_by', 'branch_ID', 'application_ID'], 'string'],
[['serial_start', 'serial_end', 'status'], 'number'],
[['created_on'], 'safe']
];
}
/**
* #inheritdoc
*/
public function attributeLabels() {
return [
'ID' => 'ID',
'account_ID' => 'Account ID',
'serial_start' => 'Serial Start',
'serial_end' => 'Serial End',
'created_on' => 'Created On',
'created_by' => 'Created By',
'branch_ID' => 'Branch ID',
'application_ID' => 'Application ID',
'status' => 'Status',
'sr' => 'ID'
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getAccount() {
return $this->hasOne(Account::className(), ['ID' => 'account_ID']);
}
public static function getActiveChequeBook($account_ID) {
return Cheque::findAll(['account_ID' => $account_ID, 'status' => array_search('Active', \common\models\Lookup::$cheque_status)]);
}
}
But executing this I get the following error:
pre>Exception 'yii\base\InvalidCallException' with message 'Setting read-only property: common\models\Account::customer'
Property customer in your common\models\Account model has no setter (only getCustomer method exists). Check you model and add appropriate property to class.
My controller is like this :
public function create()
{
$data = array(
'email' => 'chelsea#gmail.com'
);
$data = Order::where('email', $data['email'])->first();
dd($data);
}
My model order is like this :
<?php
namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
class Order extends Model
{
use SoftDeletes, Notifiable;
public $table = 'orders';
protected $dates = ['deleted_at'];
public $fillable = [
'number',
'user_id',
'store_id',
'total_amount',
'total_product',
'service_amount',
'status',
'checkout_at'
];
protected $casts = [
'number' => 'string',
'user_id' => 'integer',
'store_id' => 'integer',
'total_amount' => 'integer',
'total_product' => 'integer',
'service_amount' => 'integer',
'status' => 'integer',
'checkout_at' => 'date'
];
public static $rules = [
'user_id' => 'required',
'store_id' => 'required'
];
public function user()
{
return $this->belongsTo(User::class,'user_id','id');
}
public function store()
{
return $this->belongsTo(Store::class,'store_id','id');
}
}
table user have field id, name, email etc
table store have field id, name, email etc
I want get user name and store name from table user and table store. Then, I want store it on variable $data
How can I do it?
UPDATE
My model user is like this :
<?php
namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model
{
use SoftDeletes;
public $table = 'users';
protected $dates = ['deleted_at'];
public $fillable = [
'name',
'email',
'password',
'full_name',
'birth_date',,
'mobile_number',
];
protected $casts = [
'name' => 'string',
'email' => 'string',
'password' => 'string',
'full_name' => 'string',
'birth_date' => 'date',,
'mobile_number' => 'string',
];
public static $rules = [
'name' => 'required',
'email' => 'required'
];
}
My model store is like this :
<?php
namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Store extends Model
{
use SoftDeletes;
public $table = 'stores';
protected $dates = ['deleted_at'];
public $fillable = [
'user_id',
'domain',
'name',
'email'
];
protected $casts = [
'user_id' => 'integer',
'domain' => 'string',
'name' => 'string',
'email' => 'string'
];
public static $rules = [
'user_id' => 'required',
'domain' => 'required',
'name' => 'required'
];
public function user()
{
return $this->belongsTo(User::class,'user_id','id');
}
}
First you need to make model for User Table and Store table then define respective table names in both model after that......
public function create(Request $request)
{
$data = $request->all();
$email = 'chelsea#gmail.com';
$user = User::where('email', $email)->first();
$store = Store::where('email', $user->email)->first();
$order = Order::where('user_id', $user->id)->where('store_id', $store->id)->first();
$result = array();
$result['orderTable'] = $order;
return $result;
}
Use with in your order controller query, just pass the array of relationships that you have declared in your order model query will fetch the related tables data based on model relations, like below
In order controller
$data = Order::where('col', 'val')->with(['user','store'])->first();
In order model
public function user()
{
return $this->belongsTo(User::class,'user_id','id');
}
public function store()
{
return $this->belongsTo(Store::class,'store_id','id');
}
I have 2 Doctrine entities (Environment and EnvironmentConfig). They have a bi-directional OneToOne relationship.
Each entity has their own Fieldset so that re-use is easy.
To create an Environment it can also have an EnvironmentConfig, however not required. To allow them to be made at the same time I have an EnvironmentForm that uses the EnvironmentFieldset and the EnvironmentConfigFieldset.
The Form renders properly. However, it saves the Environment but not the EnvironmentConfig.
Where is it that I've gone wrong in setting this up and how to fix it?
Code below, leaving out getters/setters, would be too much.
Entities
// abstract class AbstractEntity has $id + getters/setters.
class Environment extends AbstractEntity
{
/**
* #var string
* #ORM\Column(name="name", type="string", length=255, nullable=false)
*/
protected $name;
/**
* #var EnvironmentConfig
* #ORM\OneToOne(targetEntity="Environment\Entity\EnvironmentConfig", inversedBy="environment")
*/
protected $config;
/**
* #var EnvironmentScript
* #ORM\OneToOne(targetEntity="EnvironmentScript")
*/
protected $script;
//Getters/setters
}
class EnvironmentConfig extends AbstractEntity
{
/**
* #var string
* #ORM\Column(name="name", type="string", length=255, nullable=false)
*/
protected $name;
/**
* #var Environment
* #ORM\OneToOne(targetEntity="Environment\Entity\Environment", mappedBy="config")
*/
protected $environment;
//Getters/setters
}
Fieldsets
class EnvironmentFieldset extends AbstractFieldset
{
/**
* {#inheritdoc}
*/
public function init()
{
//Loads id element validation
parent::init();
$this->add([
'name' => 'name',
'type' => Text::class,
'options' => [
'label' => _('Name'),
'label_attributes' => [
'class' => 'col-xs-2 col-form-label',
],
],
'attributes' => [
'id' => 'name',
'class' => 'form-control'
],
]);
$this->add([
'name' => 'environment_config',
'type' => EnvironmentConfigFieldset::class,
'options' => [
'use_as_base_fieldset' => false,
],
]);
$this->add([
'type' => ObjectSelect::class,
'name' => 'environment_script',
'options' => [
'object_manager' => $this->getEntityManager(),
'target_class' => EnvironmentScript::class,
'property' => 'id',
'display_empty_item' => true,
'empty_item_label' => '---',
'label_generator' => function ($targetEntity) {
return $targetEntity->getId() . ' - ' . $targetEntity->getName();
},
],
]);
}
}
class EnvironmentConfigFieldset extends AbstractFieldset
{
/**
* {#inheritdoc}
*/
public function init()
{
//Loads id element validation
parent::init();
$this->add([
'name' => 'name',
'type' => Text::class,
'options' => [
'label' => _('Name'),
'label_attributes' => [
'class' => 'col-xs-2 col-form-label',
],
],
'attributes' => [
'id' => 'name',
'class' => 'form-control'
],
]);
}
}
Form
class EnvironmentForm extends AbstractForm
{
/**
* EnvironmentForm constructor.
* #param null $name
* #param array $options
*/
public function __construct($name = null, array $options)
{
//Also adds CSRF
parent::__construct($name, $options);
}
/**
* {#inheritdoc}
*/
public function init()
{
//Call parent initializer. Adds submit button.
parent::init();
$this->add([
'name' => 'environment',
'type' => EnvironmentFieldset::class,
'options' => [
'use_as_base_fieldset' => true,
],
]);
}
}
Edit: added debug data and AddAction()
Above debugging done on the persist() line in the function below.
public function addAction($formName, array $formOptions = null, $route, array $routeParams = [])
{
if (!$this->formElementManager instanceof FormElementManagerV2Polyfill) {
throw new InvalidArgumentException('Dependency FormElementManagerV2Polyfill not set. Please check Factory for this function.');
}
if (!class_exists($formName)) {
throw new ClassNotFoundException('Given class could not be found. Does it exist?');
}
/** #var AbstractForm $form */
$form = $this->getFormElementManager()->get($formName, (is_null($formOptions) ? [] : $formOptions));
/** #var Request $request */
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$entity = $form->getObject();
$this->getEntityService()->getEntityManager()->persist($entity);
$this->getEntityService()->getEntityManager()->flush();
$this->flashMessenger()->addSuccessMessage(
_('Successfully created object.')
);
$this->redirectToRoute($route, $this->getRouteParams($entity, $routeParams));
}
}
return [
'form' => $form,
'validationMessages' => $form->getMessages() ?: '',
];
}
You created a field called 'environment_config' but in class Environment you called protected $config;. Both names must be the same. Same problem for 'environment_script' field and $script attribute.
Another thing, you want to create a EnvironmentConfig dynamically so you must add in $config annotation a cascade option to be able to create a $config from Environment:
/**
* #var EnvironmentConfig
* #ORM\OneToOne(targetEntity="Environment\Entity\EnvironmentConfig", inversedBy="environment", cascade={"persist"})
*/
protected $config;
I was trying to bind entity Contact with default values (using getters) to the form ContactForm using Classmethod() hydrator.
The problem is when I then call setData with a set of values, the Hydrator was not able to merge the default values and the set of values but instead it returned only the set of values. Kindly find below an excerpt of my codes.
<?php
// My contact form
namespace Application\Form;
use Zend\Form\Form;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterInterface;
class Contact extends Form
{
public function __construct($name = 'contact')
{
parent::__construct($name);
$this->add(array(
'name' => 'name',
'options' => array(
'label' => 'Your name',
),
'type' => 'Text',
));
$this->add(array(
'name' => 'subject',
'options' => array(
'label' => 'Subject',
),
'type' => 'Text',
));
$this->add(new \Zend\Form\Element\Csrf('security'));
$this->add(array(
'name' => 'send',
'type' => 'Submit',
'attributes' => array(
'value' => 'Submit',
),
));
// We could also define the input filter here, or
// lazy-create it in the getInputFilter() method.
}
public function getInputFilter()
{
if (!$this->filter) {
$inputFilter = new InputFilter();
$inputFilter->add(array('name' => 'name', 'required' => false));
$inputFilter->add(array('name' => 'subject', 'required' => false));
$this->filter = $inputFilter;
}
return $this->filter;
}
}
Here's my entity
class Contact
{
protected $name;
protected $subject;
/**
* #param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* #return mixed
*/
public function getName()
{
return $this->name;
}
/**
* #param mixed $subject
*/
public function setSubject($subject)
{
$this->subject = $subject;
}
/**
* #return mixed
*/
public function getSubject()
{
// Trying to set a default value
if (null == $this->subject) {
return 'default subject';
}
return $this->subject;
}
}
Here I test it in a controller action
class TestController extends AbstractActionController
{
public function indexAction()
{
$data = array(
'name' => 'myName'
);
$class = '\Application\Entity\Contact';
$contact = new $class;
$form = new \Application\Form\Contact();
$form->setHydrator(new ClassMethods(false));
$form->bind($contact);
$form->setData($data);
if ($form->isValid()) {
var_dump($form->getData());
}
die("end");
}
}
I wanted to get
object(Application\Entity\Contact)[---]
protected 'name' => string 'myName' (length=6)
protected 'subject' => string 'default subject' ...
But instead I got this result
object(Application\Entity\Contact)[---]
protected 'name' => string 'myName' (length=6)
protected 'subject' => null
Any idea how to make Classmethod() extract getter values from bind and merge the remaining data on setData()?
That is actually quiet easy to set the default value.
Define the default value in the entity:
class Contact
{
protected $subject = 'Default Subject';
// other properties and methods
}
In addition, you can also define the default value in the form:
$this->add(array(
'name' => 'subject',
'options' => array(
'label' => 'Subject',
),
'attributes' => array(
'value' => 'Default Subject'
),
'type' => 'Text',
));