I hava code like below. It creates a field in database and show in another places. I would like to block create a database field if message field is not exit. Rest fields are taken from system. What is wrong in my code.
$delivery->comments_buro()->create([
'name' => auth()->user()->firstname,
'user_id' => auth()->user()->id,
'message' => $request['repair_report_buro'],
'icon' => 'fa fa-commenting-o',
'style' => $position->style,
]);
Thanks for help.
You need Laravel Validations for that. Please read this: https://laravel.com/docs/5.8/validation
For example:
//controller
public function index(Request $request)
{
$validator = Validator::make($request->all(), [
'message' => 'required|string',
]);
if ($validator->fails()) {
//do validation error handling here
}
// create new row in database.
}
I have a right code. It works with it. I close this question. The right code is:
if(isset($request['repair_report_buro']) && !empty($request['repair_report_buro'])){
$delivery->comments_buro()->create([
'name' => auth()->user()->firstname,
'user_id' => auth()->user()->id,
'message' => $request['repair_report_buro'],
'icon' => 'fa fa-commenting-o',
'style' => $position->style,
]);
}
Related
Hoping someone may be able to point me in the right direction.
I have a app that consists of (among other things) Recommendations and Assessments. They are joined with a join table that includes extra fields that I would like to update but am struggling to figure out how.
As you can see above, when I create a Reccommendation, I set the following fields:
default_user_impact
default_business_impact
default_deployment_complexity
default_criticality
Now when I create a new Assessment or edit one that has not got any Recommendations linked the Assessment saves fine because nothing is needing to be written to the join table.
When I try to edit an Assessment to include one or more Recommendations, the app tries to write the link to the join table and fails because the user_impact, business_impact, deployment_complexity and criticality fields aren't specified - perfectly normal because I have set the fields to required in MySQL right? The error I get in CakePHP is
SQLSTATE[HY000]: General error: 1364 Field 'user_impact' doesn't have a default value
What I want to be able to do is at the time of editing or creating an Assessment is to use the values in the Recommendations table to populate the corresponding join table entries. Any ideas how to go about this?
So as an example:
user_impact = default_user_impact
business_impact = default_business_impact
deployment_complexity = default_deployment_complexity
criticality = default_criticality
The reason I want to do this is so that I can have the Recommendations set with values for those fields, and then if a user wants to run an assessment and they want to adjust the values just for their own assessment then it won't impact others etc.
Here is my AssessmentsTable association.
$this->belongsToMany('Recommendations', [
'foreignKey' => 'assessment_id',
'targetForeignKey' => 'recommendation_id',
'joinTable' => 'assessments_recommendations',
'through' => 'assessments_recommendations',
]);
Here is my RecommendationsTable association.
$this->belongsToMany('Assessments', [
'foreignKey' => 'recommendation_id',
'targetForeignKey' => 'assessment_id',
'joinTable' => 'assessments_recommendations',
'through' => 'assessments_recommendations',
]);
Here is my AssessmentsRecommendations association:
$this->belongsTo('Assessments', [
'foreignKey' => 'assessment_id',
'joinType' => 'INNER',
]);
$this->belongsTo('Recommendations', [
'foreignKey' => 'recommendation_id',
'joinType' => 'INNER',
]);
This is what my AssessmentsController edit function looks like:
public function edit($id = null)
{
$assessment = $this->Assessments->get($id, [
'contain' => ['Recommendations'],
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$assessment = $this->Assessments->patchEntity($assessment, $this->request->getData(), ['associated'=>['Recommendations._joinData']]);
if ($this->Assessments->save($assessment, ['associated' => ['Recommendations._joinData']])) {
$this->Flash->success(__('The assessment has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The assessment could not be saved. Please, try again.'));
}
$clients = $this->Assessments->Clients->find('list', ['limit' => 200]);
$recommendations = $this->Assessments->Recommendations->find('list', ['limit' => 200]);
$this->set(compact('assessment', 'clients', 'recommendations'));
}
Now when I've added the beforeSave function to the AssessmentsRecommendationsTable I see the following error:
Argument 2 passed to App\Model\Table\AssessmentsRecommendationsTable::beforeSave() must be an instance of App\Model\Table\EntityInterface, instance of Cake\ORM\Entity given, called in /var/www/html/csa-portal/vendor/cakephp/cakephp/src/Event/EventManager.php on line 310
Any help would be much appreciated.
First, the associations you are using are wrong. It should be like this
For AssessmentsTable
$this->hasMany('AssessmentsRecommendations', [
'foreignKey' => 'assessment_id'
]);
For RecommendationsTable
$this->hasMany('AssessmentsRecommendations', [
'foreignKey' => 'recommendation_id'
]);
For AssessmentsRecommendationsTable
$this->belongsTo('Assessments', [
'foreignKey' => 'assessment_id',
'joinType' => 'INNER',
]);
$this->belongsTo('Recommendations', [
'foreignKey' => 'recommendation_id',
'joinType' => 'INNER',
]);
Now for the default values, you have to user beforeSave in you AssessmentsRecommendationsTable.php file.You can modify your data as per your need here before the save.
public function beforeSave(Event $event, EntityInterface $entity, \ArrayObject $options)
{
if ($entity->isNew()) { // Returns true when you add new record
$recommendation = TableRegistry::getTableLocator()->get('Recommendations')->get($entity->recommendation_id);
$entity->user_impact = $recommendation->default_user_impact;
$entity->business_impact = $recommendation->default_business_impact;
$entity->deployment_complexity = $recommendation->default_deployment_complexity;
$entity->criticality = $recommendation->default_criticality;
}
}
I have never used belongsToMany, if the associations works for you then ignore the association part.
Have you considered writing a Rule to handle this?
https://book.cakephp.org/3/en/orm/validation.html#applying-application-rules
I would like to arrange my code a little bit better. I have this in view, generated by giiant:
$form->field($model, 'land_id')->dropDownList(ArrayHelper::map(app\models\Land::find()->orderBy('name')->all(), 'id', 'name'), [
'prompt' => Yii::t('app', 'Select'),
'disabled' => (isset($relAttributes) && isset($relAttributes['land_id'])),]);
Somebody has told me here on stackoverflow that it's not really nice. So I would like to transfer this part:
ArrayHelper::map(app\models\Land::find()->orderBy('name')->all(), 'id', 'name'
into model. The same applies to grid filter dropdowns:
'filter' => ArrayHelper::map(\app\models\base\Land::find()->asArray()->all(), 'id', 'name'),
Does it make sense? I think so, I hope so. I've tried to implement it in model Land 2 ways:
public function getAllAsArray() {
return ArrayHelper::map(app\models\Land::find()->orderBy('name')->all(), 'id', 'name');
}
or
public function getAllAsArray() {
return ArrayHelper::map($this->find()->orderBy('name')->all(), 'id', 'name');
}
and I wanted to call it from View/Grid (Zip - Land):
'filter' => $model->land->allAsArray,
but I'm getting the following error:
Undefined variable: model
then tried this way:
'filter' => function ($model) {$model->getLand()->one()->getAllAsArray();},
'filter' => function ($model) {$model->getLand()->getAllAsArray();},
then I get no error messages, but it's also not working.
and in Form (Zip - Land) the same way:
$form->field($model, 'land_id')->dropDownList($model->land->allAsArray(), [
'prompt' => Yii::t('app', 'Select'),
'disabled' => (isset($relAttributes) && isset($relAttributes['land_id'])),]);
but I'm getting the following error:
Call to a member function getAllAsArray() on null
Can you please point me to the right direction? I think I don't understand something basically and this disturbes me. Thank you very much in advance!
Land model
public static function getAllAsArray() {
return ArrayHelper::map(Land::find()->orderBy('name')->all(), 'id', 'name');
}
index
use app\models\Land;
'filter' => Land::getAllAsArray(),
form
use app\models\Land;
$form->field($model, 'land_id')->dropDownList(Land::getAllAsArray(), [
'prompt' => Yii::t('app', 'Select'),
'disabled' => (isset($relAttributes) && isset($relAttributes['land_id']))]);
I want to create links something like that:
http://example.com/cat1/itemname-1
http://example.com/cat1/cat2/itemname-2
http://example.com/cat1/cat2/cat3/itemname-3
http://example.com/cat1/cat2/cat3/[..]/cat9/itemname-9
How rule looks like in yii2 UrlManager and how to create links for this?
Url::to([
'param1' => 'cat1',
'param2' => 'cat2',
'param3' => 'cat3',
'slug' => 'itemname',
'id' => 3
]);
Above code is really bad for multiple category params.
I add that important is only last param it means ID.
Controller looks like that:
public function actionProduct($id)
{
echo $id;
}
The below url rule would to this trick but you have to build the "slug" with the categories within your controller:
'rules' => [
['route' => 'module/controller/product', 'pattern' => '<slug:(.*)+>/<id:\d+>', 'encodeParams' => false],
]
Generate the Url:
yii\helpers\Url::toRoute(['/module/controller/product', 'slug' => 'cat1/cat2/cat3', 'id' => 1])
The output would be:
example.com/cat1/cat2/cat3/1
view:
<p>
<?= Html::a('Download This page', ['report'], ['class' => 'btn btn-danger']) ?>
</p>
controller:
public function actionReport()
{
// setup kartik\mpdf\Pdf component
$pdf = new Pdf([
'content' => $content,
'options' => ['title' => 'Krajee Report Title'],
'methods' => [
'SetHeader' => ['Krajee Report Header'],
'SetFooter' => ['{PAGENO}'],
]
]);
return $pdf->render();
}
This function works perfectly but my html table has pagination . so i am confused how to deal with table that has pagination.
You should disable the pagination. it all depends on how you define your data provider (read more about data providers here http://www.yiiframework.com/doc-2.0/guide-output-data-providers.html). Probably you should do something like this
************* = new ActiveDataProvider([
'pagination' => false,
..............
]);
I think you can also call it like
$dataProvider->pagination =false;
Just in case you need to disable it in a specific case.
I am working on a module that requires some html to be entered to be later called upon and become part of a customer facing widget output.
I've created an administrative backend and that is all working properly, however when I enter html into the field that should be storing the data i receive an error.
I dont need the wysiwyg but I would like to be able to enter html into this value.
At this point I've not done anything special when adding the field to the fieldset. What am I missing?
$contentField = $fieldset->addField('inner_html', 'editor', array(
'name' => 'inner_html',
'style' => 'height:36em;width:36em',
'required' => false,
));
Try
$fieldset->addField('inner_html', 'editor', array(
'name' => 'inner_html',
'label' => Mage::helper('tag')->__('Description'),
'title' => Mage::helper('tag')->__('Description'),
'style' => 'width:700px; height:350px;',
'config' => Mage::getSingleton('cms/wysiwyg_config')->getConfig(array('add_variables' => false, 'add_widgets' => false,'files_browser_window_url'=>$this->getBaseUrl().'admin/cms_wysiwyg_images/index/')),
'wysiwyg' => true,
'required' => false,
));