Saving Many-to-Many Relationships with TokenInput - yii

Help me, Oh Mighty Hive Mind. You're my only hope.
I have been working on a small app for work that I'm building around a database (go figure). While I have managed to save relationship data more manually by iterating through the data, creating a new model for each, and then saving that information, I know there must be a cleaner way than this:
foreach($keys as $k) {
//Build the model to associate with keyword $k
$facts_keyword=new FactsKeyword;
$facts_keyword['fact_id']=$model->id;
$facts_keyword['keyword_id']=$k;
if(!$facts_keyword->save()) //Check for errors on saving
echo "FAILURE TO SAVE FACTS_KEYWORDS";
}
To make this work, I have made a model for the reference table between the tables facts and keywords. The reference table simply has two columns facts_id and keywords_id. I am using the TokenInput plugin for Yii to input the keywords that are associated with a given fact. The relevant view code is here:
<div id="keywords" class="row">
<?php echo $form->labelEx($keyword,'keywords'); ?>
<?php $this->widget('ext.tokeninput.TokenInput', array(
'model'=>$keyword,
'attribute'=>'name',
'url'=>array('keyword/searchKeys'),
'options' => array(
'allowCreation'=>false,
'preventDuplicates'=>true,
'resultsFormatter'=>'js:function(item){ return "<li><p>" + item.name + "</p></li>" }',
'prePopulate'=>$key,
'theme'=>'facebook',
'minChars'=>2,
)
)); ?>
<?php echo $form->error($keyword,'name'); ?>
</div>
The relationship from the fact model looks like this: 'keywords' => array(self::MANY_MANY, 'Keyword', 'facts_keywords(fact_id, keyword_id)')'
How can I save the information from the my view in a cleaner way? I have tried to change 'model'=>$keyword to 'model'=>$fact and changing 'attribute'=>'name' to 'attribute'=>'sources' That gives this error: trim() expects parameter 1 to be string, array given What am I doing wrong?

Just use this extension: activerecord-relation-behavior

Related

Laravel Queries / Controller Edits

So I am pretty new to Laravel, and I have spent the whole day fishing through various documentations but I am stuck on the way queries work within the actual application. Right now, I am trying to get some data in my database to display, and I looked at the query builder so that's where I am right now. I am also using a CRUD based admin panel for entry in the database. And since it is CRUD based, it has created the model and the controller already, so I am wondering if I need to edit any of those files to get this to work. Here is what the public function index() has right now (Using Laraadmin):
$module = Module::get('Events');
if(Module::hasAccess($module->id)) {
return View('la.events.index', [
'show_actions' => $this->show_action,
'listing_cols' => $this->listing_cols,
'module' => $module
]);
} else {
return redirect(config('laraadmin.adminRoute')."/");
}`
Obviously, I am trying to display some data from this Events table into my blade view. From what I was reading, I understood (or I thought) that it would be something similar to this:
foreach ($module as $module) {
echo $module->id;
}
But, I keep getting an error that whatever variable I pass in the loop is undefined, although I thought it was in the controller. Right now my model is just returning the view as well. Any help with this is greatly appreciated, or even just an explanation of the relationships with queries in Laravel. Thanks!
A few things to check when this happens:
Change module to a known array. This tests if your data array is set up correctly:
'module' => [ '1', '2', '3' ], // previously $module
Within the blade, now write a simple loop, such as:
#foreach ($module as $m)
{{ $m }}
#endforeach
If this version does work, then you know you have something up with your $module variable.
If the above still doesn't work, try to simplify your view request (temporarily):
view('foo', ['a' => 555]);
Then in foo.blade.php, simply have:
hello {{ a }}
EDIT
If all this seems to be correct, then the data being fetched is probably wrong (so its not a view issue). Try $module = Module::all();
It seems like you are returning a view that doesn't exist. If what you have now was correct, it would be looking for resources/views/la/events/index.blade.php Try replacing that return view line with this:
return view('events', [ ... rest of your variables ]);
And just a side note, on your foreach statement, it's probably best to use two separate variable names... so something like:
foreach ($module as $element) { ...

ClientValidation In Form not showing When I Send Id Variable To Jquery in YII

I Need Help in Yii, i get problem in my form, the problem is if i put id in textfield then client validation not showing for that field but another field no problem. This is my code in form
<div class="row">
<?php echo $form->labelEx($model,'latar_belakang'); ?>
<?php echo $form->textField($model,'latar_belakang',array('id' => 'latarbelakang','class' => 'input-block-level')); ?>
<?php echo $form->error($model,'latar_belakang'); ?>
<?php echo $form->labelEx($model,'rumusan_masalah'); ?>
<?php echo $form->textField($model,'rumusan_masalah',array('id' => 'rumusanmasalah','class' => 'input-block-level')); ?>
<?php echo $form->error($model,'rumusan_masalah'); ?>
</div>
for your knows i use id in textfield for calculaten field with jquery which i put in form . this is my jquery code in form
Yii::app()->clientScript->registerCoreScript('jquery');
Yii::app()->clientScript->registerScript('totalValues',"
function totalValues()
{
var lb = $('#latarbelakang').val() ;
var rm = $('#rumusanmasalah').val();
var tot = parseInt(lb) + parseInt(rm);
$('#nilaiakhir').val( tot );
}
", CClientScript::POS_HEAD);
Yii::app()->clientScript->registerScript('changeTotals', "
$('#latarbelakang').change( function(){ totalValues(); } );
$('#rumusanmasalah').change( function(){ totalValues();} );
", CClientScript::POS_END);
What i must do ? for solving this problem ?.
Thanks B4..
By default Yii generates ids of fields dynamically using model name and field name.
For example for 'password' field of 'User' model the id would be 'User_password'
You can inspect a field(to which you have not given your custom id) with firebug and see the auto generated id. also yii maps error messages with those auto generated ids in response. that is why your error messages are not showing.
what you can do is to try to call that js function with yii generated id.

change dataprovider to model given a relationship yii

there are two tables, percentage and stores. There is a relationship, which I can get the data of percentage from stores, such as $stores->percentageTable.
I am looking to get the data from the percentage table. Ive been doing this through a loop but I don't want to use a loop anymore. Was hoping if there is a solution by using CActiveDataProvider instead.
view: I want something like the top part. The second part is what I normally would do.
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'commission',
//looking for a solution something like this
'dataProvider'=> new CActiveDataProvider('Store',array('data'=>$commission)),
'filter'=>$model,
'columns'=>array(
'percent.commission_percent',
'percent.date_from',
'percent.date_to',
))); ?>
<?php //I don't want this anymore...
foreach($commission as $percent){
echo $percent->com_percent;
echo $percent->date_from;
echo $percent->date_to;
}
?>
Controller: I am loading based on the store and not the percentage table.
public function actionCommission($id)
{
$model=$this->loadModel($id);
$commission = $model->sellerCommissionOverrides;
$this->render('commission',array(
'model'=>$model,
'commission'=>$commission,
));
}
You need to define relation in model Store, i.e.
'percent'=>array(self::HAS_ONE, 'PercentageModel', 'store_id'),
then you will be able to use it like you want
'dataProvider'=> new CActiveDataProvider('Store'),
'filter'=>$model,
'columns'=>array(
'percent.com_percent',
'percent.date_from',
'percent.date_to',
))); ?>

Saving data from dropdown list Yii

I am trying to save values from dropdown list into my table column role.
form
<?php echo CHtml::dropDownList('role', $model, $model->getRoleOptions(),
array('empty' => '---select role---'));
?>
model
public function getRoleOptions(){
return array('1' => 'Administrator', '2' => 'Center Administrator');
}
The value is not being saved. I have also declared role as safe.
Use activeDropDownList() instead of dropDownList(). If you get a dump from your post request, you probably see invalid $_POST value with dropDownList().
activeDropDownList() method

Accessing content of textarea in Drupal-7-Theme-Form

in my custom theme-settings.php (zen-subtheme) i put following code to get a new textarea with textformat in my theme-settings:
<?php
function paper_form_system_theme_settings_alter(&$form, &$form_state) {
$form['paper_data'] = array(
'#type' => 'text_format',
'#title' => 'Put Text in here:',
'#rows' => 5,
'#resizable' => FALSE,
'#default_value' => 'xyz..',
'#format' => 'full_html'
);
}
the form is working perfektly, but when i want to access the variable by writing
<?php
$pdata = theme_get_setting('paper_data');
echo $pdata;
?>
in my page.tpl.php, the content of the variable is not rendered - instead the word "Array" is printed ...
What's wrong and why? (If i use 'textarea' as type instead of 'text_format', all is rendered well.)
You will understand when you use something like the Devel module's dpm() function to check the variable rather than echo(). Coding Drupal without the Devel module is, IMHO, folly.
The issue very likely stems from your use of the text_format type. As you can see, it saves both the textarea value as well as an associated text format. When this is used Drupal returns the data in structured form which varies depending on the type of format.
dpm() is your friend :)