I have created a form which has two ajax callbacks but neither of them seems to work as expected the form_state do not get rebuild after callback
namespace Drupal\dashboard\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\Entity\User;
use Drupal\commerce_price\Price;
use Drupal\commerce_order\Entity\OrderItem;
use Drupal\commerce_order\Entity\Order;
use Drupal\taxonomy\Entity\Term;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use CommerceGuys\Addressing\AddressFormat\AddressField;
use Drupal\dashboard\DashboardRepository;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* UI to update a record.
*
* #ingroup scorecards
*/
class AcfDataUpdateForm extends FormBase {
/**
* Our database repository service.
*
* #var \Drupal\scorecards\ScorecardsRepository
*/
protected $repository;
/**
* {#inheritdoc}
*/
public function getFormId() {
return 'acf_data_update_form';
}
/**
* {#inheritdoc}
*/
public static function create(ContainerInterface $container) {
$form = new static($container->get('dashboard.repository'));
$form->setStringTranslation($container->get('string_translation'));
$form->setMessenger($container->get('messenger'));
return $form;
}
/**
* Construct the new form object.
*/
public function __construct(DashboardRepository $repository) {
$this->repository = $repository;
}
/**
* Sample UI to update a record.
*/
public function buildForm(array $form, FormStateInterface $form_state, $order_id = NULL) {
$items = $this->repository->get_order_items($order_id);
$mark_pack = 6;
$uid = \Drupal::currentUser()->id();
$config = \Drupal::config('dashboard.settings');
foreach($items as $item){
if($item->purchased_entity == 6 || $item->purchased_entity == 7 || $item->purchased_entity == 8){
$mark_pack = $item->purchased_entity;
}
}
$form['#prefix'] = '<div id="package_design_wrapper-container">';
$form['#suffix'] = '</div>';
$form['order_id'] = array(
'#type' => 'hidden',
'#default_value' => $order_id,
);
$form['package'] = array(
'#type' => 'container',
'#prefix' => '<div class="message" id="message"></div>',
'#attributes' => array('id' => 'marketing-package-wrapper'),
);
$form['package']['marketing_package'] = array(
'#type' => 'radios',
'#default_value' => $mark_pack,
'#options' => array(
6 => $this
->t('Standard <span>'.$this->getPrice(6).'</span>'),
7 => $this
->t('Premium <span>'.$this->getPrice(7).'</span>'),
8 => $this
->t('Premium + <span>'.$this->getPrice(8).'</span>'),
),
'#disabled' => true,
);
$form['package']['designation'] = array(
'#type' => 'textfield',
'#prefix' => $this->t('<h3>your designation</h3><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry</p>'),
'#attributes' => array('placeholder' => 'Type Here'),
);
$form['package']['photograph'] = array(
'#type' => 'managed_file',
'#upload_location' => 'public://acf_profile_photos',
'#multiple' => FALSE,
'#upload_validators' => [
'file_validate_is_image' => [],
'file_validate_extensions' => array('png jpg jpeg'),
'file_validate_size' => array(25600000)
],
'#required' => true,
'#title' => $this->t('<h3>your photograph</h3><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry</p>'),
);
$form['package']['date'] = array(
'#type' => 'radios',
'#default_value' => 1,
'#options' => $this->getDates(),
'#required' => true,
'#prefix' => $this->t('<h3>Award Slot</h3><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry</p>'),
'#ajax' => [
'wrapper' => 'wrapper-dropdown',
'callback' => '::getAwardSlots',
'method' => 'replace',
'effect' => 'fade',
'event' => 'change',
'progress' => [
'type' => 'throbber',
'message' => NULL,
],
],
);
$form['package']['award_slot'] = array(
'#type' => 'radios',
'#default_value' => 1,
'#options' => $form_state->getValue('date') ? $this->getAwardSlotOptions($form_state->getValue('date')) : $this->getAwardSlotOptions('2021-04-21'),
'#prefix' => '<div id="wrapper-dropdown">',
'#suffix' => '</div>',
'#required' => true,
);
$form['package']['bio'] = array(
'#type' => 'textarea',
'#prefix' => $this->t('<h3>Individual Bio</h3><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry</p>'),
'#attributes' => array('placeholder' => 'Type Here'),
);
$form['package']['plaque_type'] = array(
'#type' => 'radios',
'#default_value' => 'remote',
'#options' => array(
'remote' => $this
->t('remote'),
'event' => $this
->t('event'),
),
'#required' => true,
'#prefix' => $this->t('<h3>Plaque Type</h3>'),
);
$form['package']['shipping_address'] = array(
'#type' => 'container',
'#states' => array(
'visible' => array(
':input[name="plaque_type"]' => array(
'value' => 'remote',
),
),
),
);
$form['package']['shipping_address']['markup'] = array(
'#markup' => ' <h3>shipping address</h3><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry</p>',
);
$form['package']['shipping_address']['address'] = array(
'#type' => 'address',
'#default_value' => ['country_code' => 'US'],
'#used_fields' => [
AddressField::GIVEN_NAME,
AddressField::FAMILY_NAME,
AddressField::ORGANIZATION,
AddressField::ADDRESS_LINE1,
AddressField::ADDRESS_LINE2,
AddressField::LOCALITY,
AddressField::POSTAL_CODE,
],
'#available_countries' => ['US'],
'#attributes' => array('class' => array('edit-address')),
);
$form['package']['save'] = array(
'#type' => 'submit',
'#submit' => ['::submitPackageDetails'],
'#name' => 'mark-save',
'#value' => t('Save'),
'#validate' => ['::validatePackageDetails'],
'#prefix' => '<div class="row"><div class="col-md-6">',
'#suffix' => '</div>',
'#ajax' => [
'wrapper' => 'package_design_wrapper-container',
'progress' => [
'type' => 'throbber',
'message' => NULL,
],
],
);
$form['package']['submit'] = array(
'#type' => 'submit',
'#submit' => ['::submitPackageDetails'],
'#validate' => ['::validatePackageDetails'],
'#name' => 'mark-submit',
'#value' => t('Submit'),
'#prefix' => '<div class="col-md-6">',
'#suffix' => '</div></div>',
'#ajax' => [
'wrapper' => 'package_design_wrapper-container',
'progress' => [
'type' => 'throbber',
'message' => NULL,
],
],
);
$form['terms'] = array(
'#type' => 'checkbox',
'#title' => t('I have read the terms & conditions and agree to comply with them. '),
'#prefix' => '<div class="row mb-3"><div class="col-12 col-sm-12 col-md-12 col-lg-12">',
'#suffix' => '</div></div>',
);
$form['#theme'] = 'acf_data_update_form';
return $form;
}
/**
* {#inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
echo "<pre>";
print_r($form_state->getValues());
die;
$old = $this->repository->save_old_data($old_data, $order_id, $user_id);
$this->messenger()->addMessage($this->t('Saved old data #entry (#count row updated)', [
'#count' => $old,
'#entry' => print_r($old_data, TRUE),
]));
if(!empty($old)){
$count = $this->repository->update_nominee($entry, $order_id, $user_id);
$this->messenger()->addMessage($this->t('Updated entry #entry (#count row updated)', [
'#count' => $count,
'#entry' => print_r($entry, TRUE),
]));
}
$form_state->setRedirect('scorecards.scorecard_entry_list');
}
public function validatePackageDetails(array &$form, FormStateInterface $form_state){
$fields = array('designation','date','award_slot','plaque_type','bio','photograph');
$add_fields = array('given_name','family_name','organization','address_line1','locality','postal_code');
$valid = true;
if($form_state->getValue('plaque_type') == 'remote'){
$add = $form_state->getValue('address');
foreach($add_fields as $field){
if(empty($add[$field])){
$form_state->setErrorByName($add[$field], 'Please enter a valid detail');
}
}
}
foreach($fields as $field){
if(empty($form_state->getValue($field))){
$form_state->setErrorByName($field, 'Please enter a valid detail');
}
}
}
public function submitPackageDetails(array &$form, FormStateInterface $form_state){
$fields = array('designation','date','award_slot','plaque_type','bio','photograph');
$add_fields = array('given_name','family_name','organization','address_line1','locality','postal_code');
if($form_state->getValue('plaque_type') == 'remote'){
$add = $form_state->getValue('address');
}
$data = array();
$pid = $form_state->getValue('marketing_package');
foreach($fields as $field){
$data[$field] = $form_state->getValue($field);
}
$data['status'] = 0;
$triggering_element = $form_state->getTriggeringElement();
$button_name = $triggering_element['#name'];
if($button_name == 'mark-submit'){
$data['status'] = 1;
}
$order_id = $form_state->getValue('order_id');
$pid = $form_state->getValue('marketing_package');
$entry = $this->repository->saveAcfDetails($order_id,$pid,$data);
$entry_add = $this->repository->saveShippingDetails($order_id,$add);
$this->setFilePermanent($form_state->getValue('photograph'));
if($entry && $entry_add){
$form_state->setRebuild(TRUE);
$this->messenger->addMessage(t('Your data has been saved successfully!'));
}
else{
$this->messenger->addMessage(t('Your data cannot be Saved'));
}
}
function getPrice($id){
$variation = \Drupal\commerce_product\Entity\ProductVariation::load($id);
return str_replace('USD','$',$variation->getPrice());
}
function setFilePermanent($image_id){
if(!empty($image_id)) {
$file = \Drupal\file\Entity\File::load($image_id[0]);
if (isset($file) and is_object($file)) {
$file->setPermanent(); // FILE_STATUS_PERMANENT;
$file->save();
}
}
}
function getDates(){
$config = $this->config('dashboard.settings');
$start_date = $config->get('conference_start_date');
$no_days = $config->get('no_days');
$dates = array();
for($i = 1; $i <= $no_days; $i++){
$j = $i-1;
$date = strtotime("{$j} day", strtotime($start_date));
$new_date = date("d-M-Y", $date);
$dates[date("Y-m-d", $date)] = 'DAY '.$i.'<span>('.$new_date.')</span>';
}
return $dates;
}
function getAwardSlots(array &$form, FormStateInterface $form_state){
$form_state->setValue('date', $form_state->getValue('date'));
$form_state->setRebuild(TRUE);
return $form['package']['award_slot'];
}
function getAwardSlotOptions($date){
$terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadByProperties(array('name' => $date));
$term = reset($terms);
$award_slots = $term->get('field_award_slot');
$slots = array();
foreach($award_slots as $award_slot){
$slots[$award_slot->value] = $award_slot->value;
}
return $slots;
}
}
I have also created a template for this form
<div class="row">
<div class="col-12 col-sm-12 col-md-9 col-lg-9">
<div class="package_border">
<div class="wellcome_back">
<div class="row">
<div class="col-12 col-sm-12 col-md-12 col-lg-12">
<h3>Awardee Deliverables</h3>
</div>
</div>
</div>
<div class="package_header">
<div class="row">
<div class="col-12 col-sm-12 col-md-5 col-lg-5">
<div class="package_header_batch">
<img src="/modules/custom/dashboard/images/package.jpg">
<div>
<h2>Marketing package</h2>
<p>Lorem Ipsum is simply</p>
</div>
</div>
</div>
{% if form.package.marketing_package %}
<div class="col-12 col-sm-12 col-md-7 col-lg-7">
{{ form.package.marketing_package }}
</div>
{% endif %}
</div>
</div>
<div class="designation_content_wrapper">
<div class="designation_content">
{{ form.package|without('marketing_package','plaque_type','shipping_address','submit','save') }}
{% if form.package.plaque_type %}
<h3>plaque</h3>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry</p>
<div class="row mb-5">
<div class="col-12 col-sm-12 col-md-6 col-lg-6">
<figure class="plaque_figure">
{% set images = getPlaqueBadge() %}
<img src="{{ images.plaque }}" width="100%">
</figure>
</div>
<div class="col-12 col-sm-12 col-md-6 col-lg-6">
<div class="plaque_type_wrapper">
{{ form.package.plaque_type }}
</div>
</div>
</div>
{% endif %}
{% if form.package.shipping_address %}
{{ form.package.shipping_address }}
{% endif %}
{{ form.package.save }}
{{ form.package.submit }}
</div>
</div>
</div>
{{ form|without('package') }}
</div>
<div class="col-12 col-sm-12 col-md-3 col-lg-3">
<aside class="package_aside">
<div class="package_aside_wrapper">
<h5>jump to</h5>
<ul class="package_aside_list">
<li>
designation
</li>
<li>
photograph
</li>
<li>
award slot
</li>
<li>
individual boi
</li>
<li>
plaque
</li>
<li>
plaque type
</li>
<li>
shipping address
</li>
</ul>
</div>
</aside>
</div>
</div>
what is actually happening is that after the ajax callback is executed the the form_state still has user submitted values which it should not. please help if anyone knows what m I doing wrong here.
That's kinda old but maybe can help someone :).
First of all - you cannot modify $form_state from within the ajax callback - so the $form_state->setRebuid() will not have an effect.
As stated in AJAX form docs you should only return a markup, a renderable array or an AjaxCommand.
What you need to do here is to modify the value of the element in the ajax callback, more like this:
function getAwardSlots(array &$form, FormStateInterface $form_state){
$date = $form_state->getValue('date')
$form['package']['award_slot']['#options'] = $this->getAwardSlotOptions($date);
return $form['package']['award_slot'];
}
Related
I just started using this library in laravel but it seems that it's not working.
This is the controller's code used:
$entries = \Lava::DataTable();
$query = Survey::select('country AS 0', \DB::raw('count(country) AS entries'))->groupBy('country')->get()->toArray();
$data = [];
foreach ($query as $q) {
$data[] = [$q[0], $q['entries']];
}
$entries->addStringColumn('Country')
->addNumberColumn('Popularity')
->addRows($data);
\Lava::GeoChart('Popularity', $entries);
return view('dashboard.homepage', ['colorsNum' => $colorsNum]);
This is my blade file:
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-body">
<div id="pop-div"></div>
#geochart('Popularity', 'pop-div')
</div>
</div>
</div>
</div>
enter image description here
It's showing this red error: Cannot read property 'style' of null
I don't know what's going wrong so please if you can help me, your help is much appreciated.
I resolved the by passing the third parameter options
$lava->GeoChart('Popularity', $popularity, [
'colorAxis' => [ 'minValue' => 0, 'colors' => ['#FF0000', '#00FF00']], //ColorAxis Options
'datalessRegionColor' => '#81d4fa',
'displayMode' => 'auto',
'enableRegionInteractivity' => true,
'keepAspectRatio' => true,
'region' => 'world',
'magnifyingGlass' => ['enable' => true, 'zoomFactor' => 7.5], //MagnifyingGlass Options
'markerOpacity' => 1.0,
'resolution' => 'countries',
'sizeAxis' => null ,
'backgroundColor'=> '#81d4fa',
]);
all
My point is.
I need to create a custom report by passing a value from $valiable in view -> controller
my question is how to pass value from $valiable
now I can get value from another system by fix value in $valiable in controller.php
but I need to pass $valiable from view.php that selected after submit button.
something like this
here my code
index.php
<?php $form = ActiveForm::begin(); ?>
<div class="col-xs-12 col-sm-6 col-md-3">
<label class="control-label"> field1 </label>
<?php echo Select2::widget([
'name' => 'field1',
'data' => Report::itemAlias('field1'),
'options' => [
'placeholder' => 'Select Cost Center...',
],
'pluginOptions' => ['allowClear' => true,],
]); ?>
</div>
<div class="col-xs-12 col-sm-6 col-md-3">
<label class="control-label"> field2 </label>
<?php echo Select2::widget([
'name' => 'field2',
'data' => Report::itemAlias('field2'),
'options' => [
'placeholder' => 'Select Fund Center...',
],
'pluginOptions' => ['allowClear' => true,],
]); ?>
</div>
<div class="form-group" >
<?= Html::submitButton('process', ['class' => 'btn btn-warning ']) ?>
</div>
<?php ActiveForm::end(); ?>
in ReportController.php
public function actionIndex ()
{
$array = []; // for array result
$field1 = ''; // if fix value $field1 = 'a'; can pass a to $result
$field2 = ''; // if fix value $field2 = 'b'; can pass b to $result
if (Yii::$app->request->isPost)
{
$FISTL = $_POST['field1']; // view ~field1
$FIPEX = $_POST['field2']; // view ~field2
}
if($field1 !== '' && $field1 !== ''){ *// add if condition for get variable*
$connection = Yii::$app->sconnection->connectionToAnotherSystem(); // connection to another system
$result = $connection->getValue([
'field1' => $field1, // if fix value $field1 = 'a'; can pass a to $result
'field2' => $field2, // if fix value $field2 = 'b'; can pass b to $result
]);
$array = array(['value' =>$result]);//return value from another system
} $dataProvider = new ArrayDataProvider([
'allModels' => $array,
]);
return $this->render('index',
[
'dataProvider' => $dataProvider, // true data
]);
}
EDIT : i got what I want. in controller.php add if condition.
I don't get it at all
But suposing you have the other system's response in $result, it looks like an array; then you are asigning an array in the variable $array that have an assosiative value called 'value'.
The way to get the field1 value is
$array['value']['field1']
You should have a GridView like this in your view php file
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
...
'value.field1',
'value.field2',
...
],
]); ?>
That should works
I am trying to diplay an error mesasge in case the field selected is duplicated in db.For this I am using laravel validation required unique. I am having problem with redirect
Here is store controller
public function store() {
$rules = array(
'car' => array('required', 'unique:insur_docs,car_id'),
);
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails()) {
// Validation has failed.
return Redirect::to('insur_docs/create')->with_input()->with_errors($validation);
} else {
$data = new InsurDoc();
$data->ownership_cert = Input::get('ownership_cert');
$data->authoriz = Input::get('authoriz');
$data->drive_permis = Input::get('drive_permis');
$data->sgs = Input::get('sgs');
$data->tpl = Input::get('tpl');
$data->kasko = Input::get('kasko');
$data->inter_permis = Input::get('inter_permis');
$data->car_id = Input::get('car');
$data->save();
// redirect
return Redirect::to('/');
}
}
Here is the route
Route::get('insur_docs/create', array('as' => 'insur_docs.create','uses' => 'Insur_DocController#create'));
create controller
public function create() {
$cars = DB::table('cars')->orderBy('Description', 'asc')->distinct()->lists('Description', 'id');
return View::make('pages.insur_docs_create', array(
'cars' => $cars
));
}
insur_docs_create.blade.php
<div id="div-1" class="body">
{{ Form::open(array('url' => 'insur_docs/store', 'class'=>'form-horizontal','id'=>'inline-validate')) }}
<div class="form-group">
{{ Form::label('ownership_cert', 'Ownership Certificate', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Form::select('ownership_cert', array('' => '', '1' => 'Yes', '0' => 'No'), '', array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid ownership certificate',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('authoriz', 'Authorization', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('authoriz', '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid authorization date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('drive_permis', 'Drive Permission', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Form::select('drive_permis', array('' => '', '1' => 'Active', '0' => 'Not active'), '', array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid drive permission',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('sgs', 'SGS', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('sgs', '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid sgs date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('tpl', 'TPL', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('tpl', isset($v->sgs) ? $v->sgs : '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid tpl date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('kasko', 'Kasko', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('kasko', isset($v->kasko) ? $v->kasko : '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid kasko date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('inter_permis', 'International Permission', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('inter_permis', '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid international permission date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('car', 'Car', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Form::select('car', $cars, Input::old('class'), array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid car',
'class' => 'form-control'))
}}
{{ $errors->first('car') }}
</div>
</div>
{{ Form::submit('Save', array('class' => 'btn btn-success btn-line')) }}
<input type="button" value="Back" class="btn btn-danger btn-line" onClick="history.go(-1);
return true;">
<div>
#foreach($errors as $error)
<li>{{$error}}</li>
#endforeach
</div>
{{ Form::close() }}
I t displays this error :
Undefined offset: 0
It might be that you are using a get, using post might help. Other than that you are mixing model and controller code. It's always a good idea to seperate these. For instance your redirects should be done inside the controller and not in the model.
http://laravel.com/docs/validation
http://laravelbook.com/laravel-input-validation/
http://culttt.com/2013/07/29/creating-laravel-4-validation-services/
It's also better to do stuff on $validator->passes() and then else return with errors.
Controller
public function store() {
$data = [
"errors" => null
];
$rules = array(
'car' => array('required', 'unique:insur_docs,car_id')
);
$validation = Validator::make(Input::all(), $rules);
if($validation->passes()) {
$data = new InsurDoc();
$data->ownership_cert = Input::get('ownership_cert');
$data->authoriz = Input::get('authoriz');
$data->drive_permis = Input::get('drive_permis');
$data->sgs = Input::get('sgs');
$data->tpl = Input::get('tpl');
$data->kasko = Input::get('kasko');
$data->inter_permis = Input::get('inter_permis');
$data->car_id = Input::get('car');
$data->save();
return Redirect::to('/');
} else {
$data['errors'] = $validation->errors();
return View::make('pages.insur_docs_create', $data);
}
}
Your errors will be available in your view under $errors. Just do a {{var_dump($errors)}} in your blade template to verify that they are there.
View
#if($errors->count() > 0)
<p>The following errors have occurred:</p>
<ul>
#foreach($errors->all() as $message)
<li>{{$message}}</li>
#endforeach
</ul>
#endif
I Think this is a really better answer from this refrenece
Laravel 4, ->withInput(); = Undefined offset: 0
withInput() doesn't work the way you think it does. It's only a function of Redirect, not View.
Calling withInput($data) on View has a completely different effect; it passes the following key value pair to your view: 'input' => $data (you get an error because you're not passing any data to the function)
To get the effect that you want, call Input::flash() before making your view, instead of calling withInput(). This should allow you to use the Input::old() function in your view to access the data.
Alternatively, you could simply pass Input::all() to your view, and use the input[] array in your view:
View::make(...)->withInput(Input::all());
which is translated to
View::make(...)->with('input', Input::all());
As for your comment, I recommend doing it like so:
$position_options = DB::table('jposition')->lists('friendly','id');
$category_options = DB::table('jcategory')->lists('friendly','id');
$location_options = DB::table('jlocation')->lists('friendly','id');
$category = Input::get('category');
$location = Input::get('location');
$type = Input:: get('type');
$data = compact('position_options', 'category_options', 'location_options', 'category', 'type', 'location');
return View::make('jobsearch.search', $data);
also thinks about laravel resource controller. because when we call no parameter get method, it redirects to the show method with ignoring our function name.
eg:-Route::get('hasith', 'Order\OrderController#hasith');----->
this parameter rederect to this function
public function show($id, Request $request) {
//code
}
In YII views folder i have test module and admin.php file to manage contents are below and i render form here where i put the code of form and dropdown in it , i want that grid refresh value of status change in dropdown
Suppose i select "Approved" than Grid show the data where status is approved
<?php
Yii::app()->clientScript->registerScript('dropdown', "
$('.dropdown-form form').submit(function(){
$('#testimonial-grid').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
");
?>
<h1>Manage Testimonials</h1>
<div class="dropdown-form">
<?php $this->renderPartial('_dropdownform',array(
'model'=>$model,
)); ?>
</div><!-- search-form -->
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'testimonial-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'created_by',
'test_name',
'test_email',
'comments',
'created_at',
/*
'status',
'approved_on',
'approved_by',
*/
array(
'class'=>'CButtonColumn',
),
),
)); ?>
Form below is _dropdownform , it contain a form and dropdown from this dropdown i am choosing the value of status
<div class="wide form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'action' => Yii::app()->createUrl($this->route),
'method' => 'get',
));
?>
<div class="row">
<?php
echo CHtml::dropDownList('status', '', array(0 => 'New', 1 => 'Approved', 2 => 'Declined'), array(
'prompt' => 'Select Status',
'ajax' => array(
'type' => 'POST',
'url' => Yii::app()->createUrl('testimonial/loadthedata'),
//or $this->createUrl('loadcities') if '$this' extends CController
'update' => '#testimonial-grid', //or 'success' => 'function(data){...handle the data in the way you want...}',
'data' => array('status' => 'js:this.value'),
)));
?>
</div>
<div class="row buttons">
<?php //echo CHtml::submitButton('Search'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- search-form -->
AND THE CODE IN MY CONTROLLER OR URL GIVEN IN DROPDOWN TO FETCH DATA IS FOLLOWING ACTION BUT I DONT KNOW HOW TO FETCH DATA FROM THIS FUNCTION AND PASS TO GRID VIEW
public function actionloadthedata() {
if (isset($_POST['status'])) {
$status = $_POST['status'];
if($status==0){
$status='New';
}
if($status==1){
$status='Approved';
}
if($status==2){
$status='Declined';
}
Testimonial::model()->findByAttributes(array('status'=>$status));
}
}
You can use CGridView property filterCssClass to link the grid filter, for example
$this->widget('CGridView', array(
'id' => 'my-list',
'filterCssClass' => '#filterFormId .filter',
And there is filter form
<?php $form = $this->beginWidget('CActiveForm', array(
'id' => 'filter-fomr-id',
)); ?>
<div class="filter clearfix">
<?php echo $form->dropDownList($model, 'name', [0=>'all', '1'=>'some else']); ?>
</div>
Replace #filterFormId .filter on jquery selector specific to you form. In other words, set id attribute for filter form, then use "#THISID .row".
In your gridview file, make sure you have this code:
Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
$('.search-form').toggle();
return false;
});
$('.search-form form').submit(function(){
$('#ad-grid').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
");
then in the CGridView definition:
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'testimonial-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
...
array(
'name'=>'Status',
'filter'=>CHtml::dropDownList('YourModel[status]', $model->status, array(0 => 'New', 1 => 'Approved', 2 => 'Declined'), array('empty' => '--all--') ),
'value'=>'( $data->status == 0) ? "New": ( $data->status == 1) ? "Approved" : "Declined"',
'htmlOptions' => array(
'style' => 'width: 40px; text-align: center;',
),
),
...
array(
'class'=>'CButtonColumn',
),
),
));
// CGridView
In order to save if/else in the 'value' section, you can implement a method in your model that returns the string associated to the integer.
It works great, just with the default Yii admin.php view, which you can edit as much as you need.
Update
Added support for empty status, does not filter query results
Thanks #Alex for your help but i am successful to make filterdropdown for grid , code is following but will you please tell me that i want that grid show only values where status=New , how i can do when page load grid show values where status is New
but first i paste the working code of dropdown filter for grid
Here is my admin.php file
<?php
$this->breadcrumbs = array(
'Testimonials' => array('index'),
'Manage',
);
$this->menu = array(
array('label' => 'List Testimonial', 'url' => array('index')),
array('label' => 'Create Testimonial', 'url' => array('create')),
);
?>
<h1>Manage Testimonials</h1>
<!-----------drop down form------------->
<?php
Yii::app()->clientScript->registerScript('dropdownfilter', "
$('.dropdown-form form #staticid').change(function(){
$.fn.yiiGridView.update('testimonial-grid', {
data: $(this).serialize()
});
return false;
});
");
?>
<div class="dropdown-form">
<?php
$this->renderPartial('_dropdownfilter', array(
'model' => $model,
));
?>
</div><!-- search-form -->
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'testimonial-grid',
'dataProvider' => $model->search(),
// 'filter' => $model,
'columns' => array(
'id',
'created_by',
'test_name',
'test_email',
'comments',
'created_at',
'status',
array(
'class' => 'CButtonColumn',
),
),
));
?>
Here is my render partial form where i place the static drop dow
<div class="wide form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'action' => Yii::app()->createUrl($this->route),
'method' => 'get',
));
?>
<div class="row">
<?php
echo CHtml::dropDownList('staticid', '', array('0' => 'New', '1' => 'Approved', '2' => 'Declined'), array(
// 'onChange' => 'this.form.submit()',
'ajax' => array(
'type' => 'POST', //request type
)));
?>
</div>
<?php $this->endWidget(); ?>
And Here is code of my adminaction in controller
public function actionAdmin() {
$model = new Testimonial('search');
$model->unsetAttributes(); // clear any default values
if (isset($_GET['staticid'])) {
$getStatus = $_GET['staticid'];
if ($getStatus == 0)
$status = 'New';
if ($getStatus == 1)
$status = 'Approved';
if ($getStatus == 2)
$status = 'Declined';
$model->status = $status;
}
if (isset($_GET['Testimonial']))
$model->attributes = $_GET['Testimonial'];
$this->render('admin', array(
'model' => $model,
));
}
Now i want that when i actionadmin triggered first time it show status=New values
i'm truly getting crazy!
I made a gallery with Meiouploader and PHPThumb. All is working very nice.
My uploaded images saved in folder img/uploads/images and in my database too.
But in the field for showing the images I only see the alt-text. Not the images.
But when In check the HTML-Code, I see the correct path to my images. But I don't see it.
What wrong???
Please help!
OK, here is all my code:
I think the paths are correct, because in source code in my browser i can see the image - Tag. Here is my code for Image-Model:
class Image extends AppModel {
var $name = 'Image';
var $validate = array(
'gallery_id' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'name' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
//'img_file' => array(
//'notempty' => array(
//'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
//),
//),
);
//The Associations below have been created with all possible keys, those that are not needed can be removed
var $belongsTo = array(
'Gallery' => array(
'className' => 'Gallery',
'foreignKey' => 'gallery_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
var $actsAs = array(
'MeioUpload' => array(
'img_file' => array(
'dir' => 'img{DS}uploads{DS}images',
'create_directory' => false,
'allowed_mime' => array('image/jpeg', 'image/pjpeg', 'image/png'),
'allowed_ext' => array('.jpg', '.jpeg', '.png'),
'zoomCrop' => true,
'thumbnails' => true ,
'thumbnailQuality' => 75,
'thumbnailDir' => 'thumb',
'removeOriginal' => true,
'thumbsizes' => array(
'normal' => array('width' => 400, 'height' => 300),
),
'default' => 'default.jpg'
)
)
);
}
Here is my code for the Images-Controller:
class ImagesController extends AppController {
var $name = 'Images';
function index() {
$this->Image->recursive = 0;
$this->set('images', $this->paginate());
}
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid image', true));
$this->redirect(array('action' => 'index'));
}
$this->set('image', $this->Image->read(null, $id));
}
function add() {
if (!empty($this->data)) {
$this->Image->create();
if ($this->Image->save($this->data)) {
$this->Session->setFlash(__('The image has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The image could not be saved. Please, try again.', true));
}
}
$galleries = $this->Image->Gallery->find('list');
$this->set(compact('galleries'));
}
function edit($id = null) {
if (!$id && empty($this->data)) {
$this->Session->setFlash(__('Invalid image', true));
$this->redirect(array('action' => 'index'));
}
if (!empty($this->data)) {
if ($this->Image->save($this->data)) {
$this->Session->setFlash(__('The image has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The image could not be saved. Please, try again.', true));
}
}
if (empty($this->data)) {
$this->data = $this->Image->read(null, $id);
}
$galleries = $this->Image->Gallery->find('list');
$this->set(compact('galleries'));
}
function delete($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid id for image', true));
$this->redirect(array('action'=>'index'));
}
if ($this->Image->delete($id)) {
$this->Session->setFlash(__('Image deleted', true));
$this->redirect(array('action'=>'index'));
}
$this->Session->setFlash(__('Image was not deleted', true));
$this->redirect(array('action' => 'index'));
}
}
Here is my code for index.ctp - View:
<div class="images index">
<h2><?php __('Images');?></h2>
<table cellpadding="0" cellspacing="0">
<tr>
<th><?php echo $this->Paginator->sort('id');?></th>
<th><?php echo $this->Paginator->sort('gallery_id');?></th>
<th><?php echo $this->Paginator->sort('name');?></th>
<th><?php echo $this->Paginator->sort('img_file');?></th>
<th class="actions"><?php __('Actions');?></th>
</tr>
<?php
$i = 0;
foreach ($images as $image):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}
?>
<tr<?php echo $class;?>>
<td><?php echo $image['Image']['id']; ?> </td>
<td>
<?php echo $this->Html->link($image['Gallery']['name'], array('controller' => 'galleries', 'action' => 'view', $image['Gallery']['id'])); ?>
</td>
<td><?php echo $image['Image']['name']; ?> </td>
<!--<td><?php echo $image['Image']['img_file']; ?> </td>-->
<td><?php echo $html->image('uploads' . DS . 'images' . DS . $image['Image']['img_file'], array('alt' => 'Gallery Image', 'width' => '400')); ?></td>
<td class="actions">
<?php echo $this->Html->link(__('View', true), array('action' => 'view', $image['Image']['id'])); ?>
<?php echo $this->Html->link(__('Edit', true), array('action' => 'edit', $image['Image']['id'])); ?>
<?php echo $this->Html->link(__('Delete', true), array('action' => 'delete', $image['Image']['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $image['Image']['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<p>
<?php
echo $this->Paginator->counter(array(
'format' => __('Page %page% of %pages%, showing %current% records out of %count% total, starting on record %start%, ending on %end%', true)
));
?>
</p>
<div class="paging">
<?php echo $this->Paginator->prev('<< ' . __('previous', true), array(), null, array('class'=>'disabled'));?>
<?php echo $this->Paginator->numbers();?>
<?php echo $this->Paginator->next(__('next', true) . ' >>', array(), null, array('class' => 'disabled'));?>
</div>
</div>
<div class="actions">
<h3><?php __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('New Image', true), array('action' => 'add')); ?></li>
<li><?php echo $this->Html->link(__('List Galleries', true), array('controller' => 'galleries', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Gallery', true), array('controller' => 'galleries', 'action' => 'add')); ?> </li>
</ul>
</div>
And here is my code for the add.ctp - View:
<div class="images form">
<?php // echo $this->Form->create('Image');?>
<?php echo $form->create('Image',array('type' => 'file')); ?>
<fieldset>
<legend><?php __('Add Image'); ?></legend>
<?php
echo $this->Form->input('gallery_id');
echo $this->Form->input('name');
//echo $this->Form->input('img_file');
echo $form->input('img_file', array('type' => 'file'));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
</div>
<div class="actions">
<h3><?php __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('List Images', true), array('action' => 'index'));?></li>
<li><?php echo $this->Html->link(__('List Galleries', true), array('controller' => 'galleries', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Gallery', true), array('controller' => 'galleries', 'action' => 'add')); ?> </li>
</ul>
</div>
I did all like in the tutorial of Jason Whydro, but it doesn't work well. It don't show me the pictures in this field, only the alt-text within and the width.
When I click on link to one of these images in my source code in my browser, then he says me: There is no object. The URL coudn't found on server!!
I hope it's enough for you to see whats going wrong. I don't see it. What did you mean with User Permission? How can I fix it, if this is the problem. I work with windows 8.
Greetings...
If your path is correctly it means that when you put this on your url bar at your browser , it shoud appears.
When it doesn't , could be a permission issue. Try to check your files permission to your http user.