I am trying to use bindModel in cakephp 3.x using below code:
$this->Member->bindModel([
[
'hasMany'=>[
'NpoMember' =>[
'className' => 'NpoMember',
'foreignKey' => 'member_id',
'conditions' => ['NpoMember.status' => 'Active'],
]
]
]
]);
but it is throwing error. Please suggest the correct syntax to bindmodel in controller in cakephp 3.x
It will work using contains after adding association in model. then you can add any number of binding using contain and . operator example:
$getPlaylistItems= $this->MyPlaylists->find()->where(['user_id'=>$_POST['user_id'],'section'=>$_POST['section']])
->contain(['PlaylistItems','PlaylistItems.DbArtists'])
->hydrate(false)->toArray();
Related
I have 2 models: Order and Product, each has belongsToMany with pivot set properly.
In OrderCrudController, I also use FetchOperation and make a fethProducts() function as below:
use \Backpack\CRUD\app\Http\Controllers\Operations\FetchOperation;
public function fetchProducts()
{
return $this->fetch([
'model' => \App\Models\Product::class,
'searchable_attributes' => ['name','sku']
]);
// return $this->fetch(\App\Models\Product::class); <-- I also tried this one
}
protected function setupCreateOperation()
{
CRUD::setValidation(OrderRequest::class);
// other fields
$this->crud->addField([
'name' => 'products',
'type' => 'relationship',
'pivotSelect' => [
'attribute' => 'name',
'ajax' => true,
],
'subfields' => [
[
'name' => 'quantity',
'type' => 'number',
],
],
]);
}
But it comes to unexpected behavior when I search the product, the select2 field remains "searching" though the request successfully retrieved the data.
screenshot - select2 field
screenshot - ajax results
PS: this field works perfectly without subfields, no vendor overrides etc., so I think I've set everything correctly.
Anyone can help?
This was asked two months ago but somehow I missed it, just noticed it today after someone opened an issue on the GitHub repository.
I am happy you guys found a solution for it but unfortunatelly I cannot recommend it as using the select2_from_ajax will miss the functionality to don't allow the selection of the same pivots twice, otherwise you will have undesired consequences when saving the entry.
I've just submitted a PR to fix this issue, I will ping you guys here when it's merged, probably by next Monday.
Cheers
I just came accross this exact problem and after quite some research and trials, i finally found a solution !
The problem seems to be related to the relationship field type inside the pivotSelect. Try to use select2_from_ajax instead and don't forget to set method to POST explicitly, that worked for me like a charm.
Here is what you might try in your case :
$this->crud->addField([
'name' => 'products',
'type' => 'relationship',
'pivotSelect' => [
'attribute' => 'name',
'type' => 'select2_from_ajax',
'method' => 'POST',
'data_source' => backpack_url('order/fetch/products') // Assuming this is the URL of the fetch operation
],
'subfields' => [
[
'name' => 'quantity',
'type' => 'number',
],
],
]);
I am currently in the process of updating old projects from cakephp 3.1.3 to 3.7.4.
For one of the projects I got the error
"_joinData" is missing from the belongsToMany results
I was unable to find any explanation to that specific error and since I am relatively new to PHP and CakePHP. and usually don't do much with databases I am currently a littlebit stuck despite lot's of information's about associations and CakePHP tables in general.
The error happens after an first() call on an model, like
$foundInstances = $instances->find()
->where([
'type_id' => $instanceTypeId,
'id' => $this->otherModel->id
])
->contain(['Features'])
->enableHydration(false);
$this->instances->first()
In the model class the relationsa re simply set like this:
$this->belongsToMany('BackendFeatures', [
'setForeignKey' => 'instance_id',
'setTargetForeignKey' => 'backend_feature_id',
'joinTable' => 'backend_features_instances'
]);
$this->belongsToMany('Features', [
'setForeignKey' => 'instance_id',
'setTargetForeignKey' => 'feature_id',
'joinTable' => 'features_instances'
]);
Can someone maybe give me an hint what i have to be looking for?
In Laravel, we can do validation on array like
$this->validate($request, [
'users.*.name' => 'bail|nullable|min:2',
'users.*.username'=>'bail|nullable|min:4|unique:t0101_user,username,' .$xx
'users.*.password' => 'bail|nullable|min:6'
], $this->messages());
In this scenario, what should i passed to the xx ?
I will need something like
users.*.id
Thank you,
(Laravel version 5.4)
Laravel Unique Validation Rule
Documentation Link
You need to manually create a validator using the unique rule
use Illuminate\Validation\Rule;
Validator::make( $data, [
'users.*.username' => [
'bail', 'nullable', 'min:4', Rule::unique( 't0101_user', 'username' )->ignore( 'users.*.id' )
]
]);
I'm using the dwightwatson/validating package to create validation rules in the model.
I particularly like the custom rulesets you can create for different routes.
Model
protected $rulesets = [
'set_up_all' => [
'headline' => 'required|max:100',
'description' => 'required'
],
'set_up_property' => [
'pets' => 'required'
],
'set_up_room' => [
'residents_gender' => 'required',
'residents_smoker' => 'required'
],
'set_up_roommate' => [
'personal_gender' => 'required',
'personal_smoker' => 'required'
]
];
Controller
$post = new Post(Input::all());
if($post->isValid('set_up_all', false)) {
return 'It passed validation';
} else {
return 'It failed validation';
}
In the above example, it works well in validating against the set_up_all ruleset. Now I would like to combine several rulesets and validate against all of them together.
According to the documentation, the package offers a way to merge rulesets. I just can't figure out how to integrate the example provided into my current flow.
According to the docs, I need to implement this line:
$mergedRules = $post->mergeRulesets('set_up_all', 'set_up_property_room', 'set_up_property');
This was my attempt, but it didn't work:
if($mergedRules->isValid()) { ...
I get the following error:
Call to a member function isValid() on array
I also tried this, but that didn't work either:
if($post->isValid($mergedRules)) { ...
I get the following error:
array_key_exists(): The first argument should be either a string or an integer
Any suggestions on how I would implement the merging rulesets?
From what I can see - mergeRulesets() returns an array of rules.
So if you do this - it might work:
$post = new Post(Input::all());
$post->setRules($post->mergeRulesets('set_up_all', 'set_up_property_room', 'set_up_property'));
if($post->isValid()) {
///
}
I've released an update version of the package for Laravel 4.2 (0.10.7) which now allows you to pass your rules to the isValid() method to validate against them.
$post->isValid($mergedRules);
The other answers will work, but this syntax is nicer (and won't override the existing rules on the model).
I've been doing the SYMFONY jobeet tuto(day 10) and once in the FORMS section, I found that some times we use :
'category_id' => new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('JobeetCategory'), 'add_empty' => false)),
and sometimes we use simply
'jobeet_affiliates_list' => new sfWidgetFormDoctrineChoice(array('multiple' => true, 'model' => 'JobeetAffiliate')),
Can anyboody explain to me WHY? and HOW is it working ?
why ,sometimes,do we use getRelatedModelName?? and why somtimes 'model' => 'myModel'???
Pretty much same thing, but, you can only use getRelatedModelName when there's a relation between the current form's model and the model you need in your widget. For example, if there's a relation defined between Article and Category, you can use getRelatedModelName('Category') in ArticleForm (usually a relation is defined).
In both cases (when a relation exists/does not exist) you can just write the model as a string 'model' => 'JobeetAffiliate'. I usually do that.