I'm using yajra/datatables, yajra/datatables-html, yajra/laravel-datatables-oracle.
I have followed the yajra/datatables-html tutorial for "edit column" with bootstraptoogle attribute and also included bootstarp toogle of js with css but bootstarp toogle is not working.
Maybe i'm missing something because if I try to show the table via Controller I can see teh data, but of course on checkbox button bootstrap toogle is not applied.
PHP Version: 7.1.3
Laravel Version: 5.8
Yajra/laravel-datatables Version: ^1.5
Yajra/laravel-datatables-html Version: ^4.4
Yajra/laravel-datatables-oracle Version: ^9.2
This is my Blade file code
{!! $html->table(['class'=>'table table-hover datatable mdl-data-table dataTable']) !!}
This is my controller function
use DataTables;
use App\Doctor;`enter code here`
use Illuminate\Http\Request;
use Yajra\DataTables\Html\Builder;
/**
* Build DataTable class.
*
*/
class AdminController extends Controller
{
public function doctor(Builder $builder)
{
if (request()->ajax()) {
$model = Doctor::query();
return DataTables::eloquent($model)
->editColumn('status', function(Doctor $doctor) {
$checkedStatus = ($doctor->status == 1) ? 'checked' : '';
return '<input type="checkbox" id="dl-admin-toggle" "'.$checkedStatus.'" data-toggle="toggle" data-on="Ready" data-off="Not Ready" data-onstyle="success" data-offstyle="danger" />';
})
->rawColumns(['status'])
->toJson();
}
$page_title = 'Doctor';
$html = $builder->columns([
['data' => 'id', 'name' => 'Id', 'title'=>'Invoice Link'],
['data' => 'name', 'name' => 'Fisrt Name', 'title'=>'First Name'],
['data' => 'status', 'name' => 'Status', 'title'=>'Status']
])->parameter([
'initComplete'=> 'function() {
$('.dl-admin-toggle').bootstrapToggle()
}
]);
return view('admin.doctor', compact('html','page_title'));
}
}
Related
All
I have Invoice model, and self reference
\\Invoice Model
public function parentInvoice()
{
return $this->hasOne('App\Invoice', 'id', 'parent_invoice_id');
}
for test in web.php it's work
Route::get('self', function () {
$parent = Invoice::find(132);
$children = $parent->parentInvoice->invoice_date;
echo $children;
// 2018-06-08 - it's work
});
but on blade don't work :( Why?
not work! - <b>Date:</b> {{$invoice->parentInvoice->invoice_date)}} <br /><br />
it's work - <div class="header">Korekta faktury nr {{ $invoice->invoice_date
}}</div>
Error: Trying to get property of non-object
Please help :(
This is my function on Invoice model:
private function generateCreditnoteInvoiceChangeData()
{
$config = InvoiceConfig::find(1);
$pdf = \PDF::loadView(
'pdf.creditnote_invoice_change_data',
array(
'config' => $config,
'invoice' => $this
)
);
return $pdf;
}
I am using laravel 5. If the validation of any field fails, I want to get the value of a particular field from the request class which I have created and it can be displayed in the view class like displaying error messages. Does anyone knows how to code for that?
above photo, for the id part how to make the syntax to return the value?
Controller :
public function edit(Requests\EventRequest1 $request){
$date=$_POST['eventDate'];
$title=$_POST['title'];
$id=$_POST['id'];
$events=EventCal::findOrFail($id);
$events->update($request->all());
DB::table('event_cals')
->where('id',$id)
->update(['title' => $title,'eventDate' => $date]);
return redirect('/dcalendar');
}
Model :
class EventCal extends Model {
protected $fillable = [
'title',
'eventDate',
];
}
View :
#if($errors->has('title') )
<td><ul class="alert alert-danger" style="width: 250px;height: 40px"> {{$id}}</ul></td>
#endif
#if($errors->has('eventDate'))
<td><ul class="alert alert-danger" style="width: 250px;height: 40px"> {{$errors->first('eventDate')}}</ul></td>
#endif
EventRequest1(Request Class) :
public function rules()
{
return [
'title' => 'required',
'eventDate' => 'required|date|after:yesterday',
'id' => Request::get('id')
];
}
public function messages(){
return [
'title.required' => 'Title is required.',
'eventDate.after' => 'Event Date is passed.',
'eventDate.required' => 'Event Date is required.',
];
}
I want to return the id for view page. In the view page {{$id}} should print the id value.Is there any way? I'm not sure how to return the value of id from request. That's the only thing I needed to know.
Inside of your request class you must override the response() function:
public function response(array $errors)
{
return $this->redirector->back()
->withInput($this->except($this->dontFlash))
->withErrors($errors)
->with('id', $this->get('id'));
}
I have two models in Yii2 (masterTransaction and splitTransaction), where each masterTransactions can have multiple splitTransactions. Each splitTransaction has an attribute 'amount'. My problem is I need to validate if the sum over all 'amount' attributes is 0.
My first solution was to make another model called Transaction, in which I had an attribute where I saved an instance of the masterTransaction model and another attribute with an array of splitTransaction instances. I did the validation with a custom inline validatior, which work perfectly.
Transaction model
class Transaction extends Model
{
public $masterTransaction;
public $splitTransactions;
public function init()
{
$this->masterTransaction = new MasterTransaction();
$this->splitTransactions[] = new SplitTransaction();
}
public function rules()
{
return [
['splitTransactions', 'validateSplitTransactions'],
];
}
public function validateSplitTransactions($attribute, $params)
{
$sum = 0;
foreach ($this->$attribute as $transaction) {
$sum = bcadd($sum, $transaction->amount, 3);
}
if ($sum != 0) {
$this->addError($attribute, 'The sum of the entries has to be 0');
}
}
public function save()
{
$this->masterTransaction->save();
foreach ($this->splitTransactions as $splitTransaction) {
$splitTransaction->master_transaction_id = $this->masterTransaction->id;
$splitTransaction->save();
}
}
}
Controller function to create the model
public function actionCreate()
{
$transaction = new Transaction();
$count = count(Yii::$app->request->post('SplitTransaction', []));
for ($i = 1; $i < $count; $i++) {
$transaction->splitTransactions[] = new SplitTransaction();
}
if ($transaction->masterTransaction->load(Yii::$app->request->post()) && Model::loadMultiple($transaction->splitTransactions, Yii::$app->request->post())) {
$transaction->masterTransaction->user_id = Yii::$app->user->id;
foreach ($transaction->splitTransactions as $splitTransaction) {
$splitTransaction->user_id = Yii::$app->user->id;
}
if ($transaction->validate()) {
$transaction->save();
}
}
return $this->render('create', [
'transaction' => $transaction,
]);
}
But when I tried building a form to input the data, I ran into a problem with the Ajax validation. The validation would work, but Yii didn't know where to put the error message, so it just deleted it.
I suspect that this is just not the preferred way in Yii2 model my data, but I don't really have another idea. Maybe someone has some ideas for me.
Option 1.
It depends on your view file codes. Does your form contains "splitTransactions" variable? If not, you can put it like this
<?= $form->field($model, 'splitTransactions')->hiddenInput(['maxlength' => true])->label(false); ?>
The variable will be hidden, but still show errors. In some case validation will not be fired because of empty value of "splitTransactions" variable.
"splitTransactions" should contain some value to fire validation. You can put some value to if before pasting the form like this
$model->splitTransactions=1;
Option 2.
You can add error to other variable (which form contains) like this
public function validateSplitTransactions($attribute, $params)
{
$sum = 0;
foreach ($this->$attribute as $transaction) {
$sum = bcadd($sum, $transaction->amount, 3);
}
if ($sum != 0) {
$this->addError('transaction_number', 'The sum of the entries has to be 0');
}
}
Look, form should contain "transaction_number" variable. Error will be added to "transaction_number" input.
Option 3. In my experience.
It is better to separate ajax validation from form action url a.g. create another controller action for ajax validation and use it.
Example
Create model FeedbackForm
class FeedbackForm extends Model
{
public $name;
public $email;
public $text;
/**
* #inheritdoc
*/
public function rules()
{
return [
[['name', 'email', 'text'], 'required'],
[['name', 'email'], 'string', 'max' => 128],
[['email'], 'email'],
[['text'], 'string', 'max' => 512],
];
}
public function attributeLabels()
{
return [
'name' => \Yii::t('front', 'Name'),
'email' => \Yii::t('front', 'Email'),
'text' => \Yii::t('front', 'Message text'),
];
}
}
put actions to SiteSontroller
public function actionFeedback()
{
$model= new \frontend\models\FeedbackForm;
$model->load(Yii::$app->request->post());
if($model->validate()) {
$newFeed=new \frontend\models\Feedback;
$newFeed->create_time=new \yii\db\Expression('NOW()');
$newFeed->name=$model->name;
$newFeed->email=$model->email;
$newFeed->is_new=1;
$newFeed->text=$model->text;
if($newFeed->save()) {
\Yii::$app->session->setFlash('success', \Yii::t('front', 'Your message has accepted'));
} else {
\Yii::$app->session->setFlash('error', \Yii::t('front', 'Error on save'));
}
} else {
\Yii::$app->session->setFlash('error', \Yii::t('front', 'Data error'));
}
return $this->redirect(['/site/index']);
}
public function actionFeedbackvalidate()
{
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model= new \frontend\models\FeedbackForm;
$model->load(Yii::$app->request->post());
return ActiveForm::validate($model);
}
And create form inside view
<?php $model=new \frontend\models\FeedbackForm; ?>
<?php $form = ActiveForm::begin([
'enableClientValidation' => true,
'enableAjaxValidation' => true,
'validationUrl'=>['/site/feedbackvalidate'],
'validateOnSubmit' => true,
'id' => 'form-feedback',
'action'=>['/site/feedback'],
'options'=>['class'=>'some class', 'autocomplete'=>'off']
]); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true, 'placeholder'=>$model->getAttributeLabel('name'), 'autocomplete'=>'off'])->label(false); ?>
<?= $form->field($model, 'email')->textInput(['maxlength' => true, 'placeholder'=>$model->getAttributeLabel('email'), 'autocomplete'=>'off'])->label(false); ?>
<?= $form->field($model, 'text')->textarea(['maxlength' => true, 'placeholder'=>$model->getAttributeLabel('text'), 'autocomplete'=>'off'])->label(false); ?>
<div class="form-group">
<input type="submit" class="btn btn-default" value="<?php echo Yii::t('front', 'Send') ?>">
</div>
<?php ActiveForm::end(); ?>
That is it
I have a list of checkboxes, which aren't associated with the model itself like the rest of the form:
echo Html::checkboxList('options', $selected_options, $options, ['class' => 'checkbox']);
In the model I have a following rules:
public function rules() {
return [
....*/
[['options'], 'integer'],
['options', 'optValidation', 'on' => 'update'],
];
}
And the following validator:
public function optValidation($attribute, $params) {
foreach ($attribute as $attr){
if ($attr == 1) {
$return = true;
}
else {
$return = false;
}
}
if (!$return) {
$this->addError($attribute, 'At least one checkbox has to be selected!');
}
}
Unfortunately nothing happens when submitting the form as if there are no rules for validation of the field 'options'. Where's the catch?
You need to add options as a public attribute inside your model class. Then you need to set it as safe inside your rules:
public function rules() {
...
[['options'], 'integer'],
[['options'], 'optValidation', 'on' => 'update'],
[['options'], 'safe'],
...
Finally, you will have to generate the input just like other inputs related to your model, even if it doesn't exist in your DB table, you need it inside your model:
<?php echo $form->field($model, 'options')->checkboxList('options', $selected_options, $options, ['class' => 'checkbox']); ?>
I'm new to the Yii Framework. Currently, I'm having a project which require me to use Yii framework. I would like to ask, is it possible for me to validate an attribute which is not save inside the database?
case:
I have a checkbox which require the user to tick on it in order to move to the next page. If the user doesn't tick on it, then it will prompt an error. How to I validate it in Yii format?
Can someone teach me how to change the validation below to fit Yii Format? where should the validation locate?
content in model.php
public $pdpa_agree;
public function rules()
{
array('pdpa_agree', 'required');
}
content in view.php
<?php
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
'id'=>'pdpaPolicy-form',
'enableAjaxValidation'=>true,
'type'=>'horizontal',
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
"autocomplete"=>"off", //turn off auto complete in FF
)
));
?>
<?php echo $data->pdpa_content; ?>
<p class="cb_pdpa" style="font-weight:bold"><?php echo $form->checkbox($data,'pdpa_agree'); ?> I have read and understood the above policies and hereby give consent for CTES to use my <pd>*personal data</pd> in accordance to the policies listed out above.</p>
<div class="form-actions">
<?php
/*$this->widget('bootstrap.widgets.TbButton', array(
'buttonType' => 'submit',
'type' => 'primary',
'label'=>$model->isNewRecord ? 'PolicyAgreement' : 'Continue Registration',
));*/
?>
<input type="button" name="submit" value="Continue Registration" onclick="validateAgreement()">
</div>
<?php $this->endWidget(); ?>
<script>
function validateAgreement()
{
if($("#pdpa_agree").is(':checked'))
{
window.location.href = 'register?sourceID=CTES';
return true;
}
else
{
alert("Please tick on the agreement checkbox in order to proceed the registration!");
return false;
}
}
</script>
How to turn to validation below to fit Yii Format?
<script>
function validateAgreement()
{
if($("#pdpa_agree").is(':checked'))
{
window.location.href = 'register?sourceID=CTES';
return true;
}
else
{
alert("Please tick on the agreement checkbox in order to proceed the registration!");
return false;
}
}
</script>
Yeah you can validate
Model.php
Delclare the variable you want to use
public $pdpa_agree;
public function rules()
{
array('pdpa_agree', 'required');
}
public function attributeLabels()
{
return array(
'pdpa_agree' => 'I have read and understood the above policies and hereby give consent for CTES to use my *personal data in accordance to the policies listed out above',
);
}
MyController.php
public function actionRegistration(){
$model = new Model();
if(isset($_POST['Model'])){
//Stuff to save Goes here
}
$this->render('registration');
}
view.php
<?php
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
'id'=>'pdpaPolicy-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'type'=>'horizontal',
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
"autocomplete"=>"off", //turn off auto complete in FF
)
));
?>
<?php echo $data->pdpa_content; ?>
<div class="form-actions">
$form->checkBox($model,'checkBox');
$form->labelEx($model,'checkBox');
$form->error($model,'checkBox');
</div>
<?php $this->endWidget(); ?>