i have problem with selected dropdown,where i click form edit.dropdown can't selected empty(choose)if data no there in database.
i want if data empty,dropdown like this:
so here my code:
//mycontroller
public function edit($id) {
$data = array(
'title' => 'Users',
'breadcrumb'=> 'User Edit',
'groups' => $this->groups->get_all(),
'position' => $this->users->get_position(),
'report' => $this->users->get_leader(),
'users' => $this->users->get_by(array('nik' => $id)),
'content' => 'edit'
);
$this->load->view ('default', $data);
}
//my model
public function get_leader()
{
$idstat=array(4);
$this->db->select('nik');
$this->db->select('username');
$this->db->from('t_mtr_employee');
$this->db->where_in('t_mtr_employee.group_id',$idstat);
$query= $this->db->get();
return $query->result();
}
<div class="form-group">
<label class="control-label col-md-3">Reporting To<span
class="required"> * </span></label>
<div class="col-md-6">
<select class="form-control" name="reporting">
<option disabled>Choose</option>
<?php
$id = $users->nik;
foreach($report as $report) {
$selected = $id == $report->nik ? 'selected' : '';
echo '<option '.$selected.' value="'.$report->nik.'">'.$report->username.'</option>';
}
?>
</select>
</div>
</div>
code view above can't show where data dropdown selected,i want when i click form edit dropdown has selected.
where is my wrong code,how to resolve it?
Here is the process I used to figure this out... I've left in all the debug - testing/validation for proving the concept as an extra bonus to help show how to figure this stuff out...
I hope it's useful
<?php
/**
* Test code for Selection dependant upon database entries
*/
/**
* So we want to...
* 1. Build the Selections from the Databsae
* 2. Set the id to choose the selection
*
* #var object $users
*/
// Simulate the Data from the Database for creating the Selection Dropdown
$reports_to_object = [
(object) [ 'nik' => 1, 'username' => 'Fred' ],
(object) [ 'nik' => 2, 'username' => 'Sam' ],
(object) [ 'nik' => 3, 'username' => 'George' ]
];
$reports = (object) $reports_to_object;
// We expect when there is no entry from the Database
// our id will be set to 0.
$id = 3; // Change this for testing
// Results:
// 0 = Choose - Is correctly Selected
// 1 = Fred - Is correctly Selected
// 2 = Sam - Is correctly Selected
// 3 = George - Is correctly Selected
var_dump($reports); // make sure our mockup data is correct
?>
<form>
<div class="form-group">
<label class="control-label col-md-3">Reporting To<span
class="required"> * </span></label>
<div class="col-md-6">
<select class="form-control" name="reporting">
<?php
// DEBUG - Remove this as we are manually setting it.
// $id = $users->nik;
$selected = ( $id == 0 ) ? 'selected' : '';
echo '<option value="0" ' . $selected . '>Choose</option>';
foreach ( $reports as $report ) {
$selected = ( $id == $report->nik ) ? 'selected' : '';
echo '<option value="' . $report->nik . '" ' . $selected . '>' . $report->username . '</option>';
}
?>
</select>
</div>
</div>
</form>
Related
I'm struggling with this. I add multiple custom field values: in this case event dates with their title and location to all my projects (custom post type) and want to display them in a table together on a page called Calendar. I tried to query the posts but then the custom fields will show as groups together, and not as a date ordered list.
The event titles match the post title in this case.
My question is: what would be the best solution? Creating all the event dates as custom fields within the posts and then show them all together on a single page called calendar, or create them all in a calendar page and then filter those on title to show only the relevant ones in a single post that match the page title?
The event name is taken from a post object, which seemed the best solution for the scenario where all events are created on the same page, but other wise I might use just the post title.
Hope there is someone to help!
My code for the calendar (the part with upcoming dates):
<div class="Rtable upcoming Rtable--collapse">
<?php $outs = array(); if( have_rows('events') ): ?>
<?php while ( have_rows('events') ) : the_row(); ob_start();
// Get sub field values.
$date = get_sub_field('date');
$location = get_sub_field('location');
$website = get_sub_field('website');
$title = get_sub_field('title');
$premiere = get_sub_field('premiere');
$event = get_sub_field('date', false, false);
$today = strtotime(date('Ymd'));
$upcoming = strtotime($event);
$datefin = new DateTime($event); ?>
<?php if ($upcoming >=$today): ?>
<div class="Rtable-cell Rtable-cell--head <?php if( get_sub_field('premiere') == 'yes' ): ?>premiere <?php endif; ?>">
<?php if( get_sub_field('date') ): ?><?php the_sub_field('date'); ?><?php endif; ?>
</div>
<div class="Rtable-cell table-project-title"><?php if( get_sub_field('premiere') == 'yes' ): ?><span style="color: var(--magenta);">premiere:</span> <?php endif; ?>
<?php if( $title ): ?><?php foreach( $title as $post ):
// Setup this post for WP functions (variable must be named $post).
setup_postdata($post); ?><?php the_title(); ?> <?php endforeach; ?> <?php
// Reset the global post object so that the rest of the page works correctly.
wp_reset_postdata(); ?> <?php endif; ?>
</div>
<div class="Rtable-cell"><?php if( get_sub_field('location') ): ?><?php the_sub_field('location'); ?><?php endif; ?></div>
<div class="Rtable-cell Rtable-cell--foot"><?php if( get_sub_field('website') ): ?><a class="button" href="<?php echo esc_url( $website ); ?>" target="_blank">Tickets</a> <?php endif; ?></div>
<?php endif; ?>
<?php $outs[] = ob_get_clean(); endwhile; ?>
<?php
else :
endif;
$outs = array_reverse($outs);
echo implode($outs);
?>
</div><!-- UPCOMING END -->
I found the solution, to query by the custom field date. Result here:
<?php
/**
* Template Name: Calendar
*/
get_header();
?>
<?php get_header();
?>
<div class="content-header yellow">
<h1><?php the_title();
?></h1>
</div>
<!-- Kalender -->
<div class="yellow content">
<div class="Rtable upcoming Rtable--collapse">
<?php
// Create an empty array for storage
$post_data = array();
// Set arguments for your query
$args = array(
'post_type' => 'projects',
'posts_per_page' => -1
);
// Do our query with any arguments from above
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// Setup our repeater
if ( have_rows( 'events' ) ):
while ( have_rows( 'events' ) ) : the_row();
// Optional - Only get posts that match a true false within our repeater
$event = get_sub_field( 'date', false, false );
$today = strtotime( date( 'Ymd' ) );
$upcoming = strtotime( $event );
$datefin = new DateTime( $event );
if ( $upcoming >= $today ) {
// Build our array with the data we need using key => value
$post_data[] = array(
'url' => get_the_permalink(),
'title' => get_the_title(),
'date' => get_sub_field( 'date' ),
'location' => get_sub_field( 'location' ),
'website' => get_sub_field( 'website' ),
);
}
endwhile;
endif;
}
} ?>
<?php // Custom function to use in our sort to list the items by date
function subval_sort( $a, $b ) {
if ( $a['date'] == $b['date'] )
return 0;
return $a['date'] < $b['date'] ? -1 : 1;
}
// Sort our multidimensional array by sub array value
usort( $post_data, 'subval_sort' );
// We can now work our data normally through easy to access methods
foreach ( $post_data as $post ) {
?>
<div class="Rtable-cell Rtable-cell--head <?php if( get_sub_field('premiere') == 'yes' ): ?>premiere <?php endif; ?>">
<?php $format_in = 'm/d/Y';
// the format your value is saved in ( set in the field options )
$format_out = 'd/m/Y';
// the format you want to end up with
$date = DateTime::createFromFormat( $format_in, $post['date'] );
echo $date->format( $format_out ) . ' ' ;
?>
</div>
<div class="Rtable-cell table-project-title"><?php if ( get_sub_field( 'premiere' ) == 'yes' ): ?><span style="color: var(--magenta);">premiere:</span> <?php endif;
?>
<a href="<?php echo $post['url']; ?> ">
<?php
echo $post['title'] . ' ' ;
?>
</a>
</div>
<div class="Rtable-cell">
<?php echo $post['location'] . ' ' ;
?>
</div>
<div class="Rtable-cell Rtable-cell--foot">
<a class="button" href="<?php
echo $post['website']; ?> ">
tickets
</a>
</div>
<?php }
?>
</div>
</div>
<?php get_footer();
?>
I'm working with Codeigniter, on a sales targets' form for salesmen.
They have to input values for each product, locality, year, etc.
Product and locality are already get with existing database: no need to set rules (see controller).
When I checked the post (with enable_profiler of Codeigniter), I get this:
The problem is these datas don't insert into the database table.
I read and tested a lot, but always blocked.
Here is my model:
public function add($params)
{
$this->db->insert($this->table, $params);
return $this->db->insert_id();
}
My controller:
$this->load->library('form_validation');
$this->form_validation->set_rules('year', 'Year', 'required|integer');
$this->form_validation->set_rules('prevision', 'Prevision', 'required');
$this->form_validation->set_rules('value', 'Value', 'required|integer');
if ($this->form_validation->run()) {
$params = array(
'year' => $this->input->post('year'),
'prevision' => $this->input->post('prevision'),
'locality_id' => $this->input->post('locality'),
'product' => $this->input->post('product'),
'value' => $this->input->post('value'),
);
$this->Objectif_model->add($params);
redirect('admin/objectif');
} else {
$this->layout('admin/objectif/add');
}
And my view with inputs:
<?php foreach ($products as $product) : ?>
<tr class="form-group">
<td class="bg-warning">
<?= $product->grp_product; ?>
</td>
<td class="bg-warning product">
<?= $product->code; ?>
</td>
<?php foreach ($localities as $locality ) : ?>
<td>
<input type="text" class="form-control valeur" placeholder="Value k€" name="value[]" data-validation="number" data-validation-ignore="./" data-validation-optional="true" />
<input type="text" name="year[]" />
<input type="text" name="prevision[]" />
<input type="text" name="product[]" value="<?= $product->code ?>" />
<input type="text" name="localite_id[]" value="<?= $locality->id ?>" />
</td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
Hope you will help me.
I find my answer.
In my controller, I had to pass each post in a variable and made a loop.
//action post in a var for each data
$id = $this->input->post('id');
$prev = $this->input->post('prevision');
$year= $this->input->post('year');
$locality_id = $this->input->post('locality_id');
$product = $this->input->post('product');
$value= $this->input->post('value');
if ($this->form_validation->run()) {
$count_id = count($id);
if (isset($id)) {
for ($i = 0; $i < $count_id; $i++) {
$obj[$i] = array(
'id' => $id[$i],
'prevision' => $prev,
'year' => $year,
'locality_id' => $locality_id[$i],
'product' => $product[$i],
'value' => $value[$i]*1000
);
} // endfor
if (isset($obj)) {
$this->Objectif_model->add_obj($obj);
} // endif
}// endif isset
}// endif form validation
I'm trying to save various instances of a field using the dynamic form widget. The problem I'm having is that after I submit it only saves the last value at input.
<div class="row">
<div class="panel panel-default">
<div class="panel-heading"><h4><i class="glyphicon glyphicon-plus"></i> Facilidades a realizar y costo estimado:</h4></div>
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 4, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelosfacilidades[0],
'formId' => 'dynamic-form',
'formFields' => [
'Descripcion',
'precio',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelosfacilidades as $i => $modelofacilidad): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Descripción de facilidad y precio</h3>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelofacilidad->isNewRecord) {
echo Html::activeHiddenInput($modelofacilidad, "[{$i}]id");
}
?>
<?= $form->field($modelofacilidad, "[{$i}]Descripcion")->textArea(['maxlength' => true]) ?>
<div class="row">
<div class="col-sm-6">
<?= $form->field($modelofacilidad, "[{$i}]precio")->textInput(['placeholder' => '$']) ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
This is a function Gii generated at my form model for the field that receives the data.
/**
* #return \yii\db\ActiveQuery
*/
public function getFacilidadesARealizar0025s()
{
return $this->hasMany(FacilidadesARealizar0025::className(), ['id_0025' => 'id_asda_pa_0025']);
}
And this is the actionCreate controller class:
public function actionCreate()
{
$model = new AsdaPa0025();
$modelosfacilidades = [new FacilidadesARealizar0025()];
if ($model->load(Yii::$app->request->post())) {
$model->cuerdas= $model->propia + $model->usofructo + $model->arrendada;
$model->file = UploadedFile::getInstance($model, 'file');
$modelosfacilidades = Model::createMultiple(FacilidadesARealizar0025::classname());
Model::loadMultiple($modelosfacilidades, Yii::$app->request->post());
//valida los modelos
$valid = $model->validate();
$valid = Model::validateMultiple($modelosfacilidades) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelosfacilidades as $modelofacilidades) {
//Aqui le digo al controlador que id_0025 es igual al id de la instancia de la forma 0025
$modelofacilidades->id_0025 = $model->id_asda_pa_0025;
if (! ($flag = $modelofacilidades->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
$model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
return $this->redirect(['view', 'id' => $model->id_asda_pa_0025]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
// $model->file = 'uploads/' . $model->imageFile->baseName . '.' . $model->imageFile->extension;
// if ($model->save()) {
// $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
// return $this->redirect(['view', 'id' => $model->id_asda_pa_0025]);
}
else{
// return $this->redirect(['view', 'id' => $model->id_asda_pa_0025]);
return $this->render('create', [
'model' => $model,
'modelosfacilidades' => (empty($modelosfacilidades)) ? [new FacilidadesARealizar0025] : $modelosfacilidades
]);
}
}
I would appreciate any help! I can't seem to find the answer to my problem anywhere.
1)Make sure that Active form has the same id as the formId in your DynamicFormWidget:
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
2)Change [new FacilidadesARealizar0025()] to [new FacilidadesARealizar0025];
3) After if ($model->load(Yii::$app->request->post())) {
add
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return Yii::$app->request->post();
and make sure that all your FacilidadesARealizar0025 model data is submitted. This helps you determine whether the problem is in your form or your create function. If not all your data is posted then focus on your form. I hope this helps
At customer registration:
By default, Magento uses the supplied customer name to auto-populate the default shipping / billing information. We are a B2B, and need to gather that information separately at the time of registration. Additionally, we need to get the address fax number.
These are not custom attributes (already made a bunch of those, and have integrated them into a greatly expanded registration form), but the standard first name, last name and fax fields associated with a customer address.
I've attempted this:
<span class="msg">Default shipping and billing information.</span>
<ul class="form-list">
<li class="fields">
<div class="field billing_name">
<label for="billing_firstname" class="required"><em>*</em><?php echo $this->__('First Name') ?></label>
<div class="input-box">
<input type="text" name="billing_firstname" id="billing_firstname" value="<?php echo $this->htmlEscape($this->getFormData()->getFirstName()) ?>" title="<?php echo $this->__('First Name') ?>" class="input-text required-entry" />
</div>
</div>
<div class="field billing_name">
<label for="billing_lastname" class=""><em>*</em><?php echo $this->__('Last Name') ?></label>
<div class="input-box">
<input type="text" name="billing_lastname" id="billing_lastname" value="<?php echo $this->htmlEscape($this->getFormData()->getLastName()) ?>" title="<?php echo $this->__('Last Name') ?>" class="input-text required-entry" />
</div>
</div>
</li>
but I'm not clear what the input name should be. Whatever the case, the account names are used instead.
Looking for a little information on maybe the "name" of the form fields required, and some method of disabling the auto-populate feature, should that also be required.
cheers
Update
Looking at this a little more closely.
I'm overriding the mage/customer/controller/accountController.php :: createPostAction() and I see in the controller the location where the form is processed and populated as a customer entity.
I'm trying something like this
if ($this->getRequest()->getPost('create_address')) {
/* #var $address Mage_Customer_Model_Address */
$address = Mage::getModel('customer/address');
/* #var $addressForm Mage_Customer_Model_Form */
$addressForm = Mage::getModel('customer/form');
$addressForm->setFormCode('customer_register_address')
->setEntity($address);
$addressData = $addressForm->extractData($this->getRequest(), 'address', false);
$addressErrors = $addressForm->validateData($addressData);
if ($addressErrors === true) {
$address->setId(null)
->setIsDefaultBilling($this->getRequest()->getParam('default_billing', false))
->setIsDefaultShipping($this->getRequest()->getParam('default_shipping', false));
$addressForm->compactData($addressData);
// attempting to jam vars into address obj
$address['_data']['firstname'] = $this->getRequest()->getPost('billing_firstname');
$address['_data']['lastname'] = $this->getRequest()->getPost('billing_lastname');
$address-['_data']['fax'] = $this->getRequest()->getPost('billing_fax');
// end
Mage::log('createPostAction, after var jam: '. print_r($address, true ) );
$customer->addAddress($address);
$addressErrors = $address->validate();
if (is_array($addressErrors)) {
$errors = array_merge($errors, $addressErrors);
}
} else {
$errors = array_merge($errors, $addressErrors);
}
}
When i log this out:
2012-12-18T01:51:10+00:00 DEBUG (7): createPostAction, after var jam: Mage_Customer_Model_Address Object
(
[_customer:protected] =>
[_eventPrefix:protected] => customer_address
[_eventObject:protected] => customer_address
[_resourceName:protected] => customer/address
[_resource:protected] =>
[_resourceCollectionName:protected] => customer/address_collection
[_cacheTag:protected] =>
[_dataSaveAllowed:protected] => 1
[_isObjectNew:protected] =>
[_data:protected] => Array
(
[entity_type_id] => 2
[entity_id] =>
[is_default_billing] => 1
[is_default_shipping] => 1
[firstname] => Chirp // customer firstname
[lastname] => Anaplex // customer lastname
[company] => some agency
[street] => 2345 somewhere dr
[city] => somecity
[country_id] => US
[region] =>
[region_id] => 44
[postcode] => 84151
[telephone] => 123-123-1233
)
[_hasDataChanges:protected] => 1
[_origData:protected] =>
[_idFieldName:protected] => entity_id
[_isDeleted:protected] =>
[_oldFieldsMap:protected] => Array
(
)
[_syncFieldsMap:protected] => Array
(
)
)
The form variables are getting passed successfully ( i see them in the log ), but I seem to be unable to insert them into the address object this way. I get the following Notice:
2012-12-18T16:39:39+00:00 ERR (3): Notice: Indirect modification of overloaded element of Mage_Customer_Model_Address has no effect in /root/namespace/module/controllers/AccountController.php on line 79
If this is "Indirect" - what is the "Direct" method?
Anyone?
Derp. This works.
$address->setData('firstname', $this->getRequest()->getPost('billing_firstname'));
$address->setData('lastname', $this->getRequest()->getPost('billing_lastname'));
$address->setData('fax', $this->getRequest()->getPost('billing_fax'));
Anyone else needing this?
Add form fields into your/theme/template/persistent/forms/register.phtml
override Mage_Customer_AccountController
setData('key', 'value') in yourmodule/customer/controller/accountController.php :: createPostAction()
I am using Symfony 1.4, and am using embedded forms to place multiple similar forms into one form for a configuration page. I am having success showing the form, but the default values of the sfWidgetFormChoice widgets are not being rendered, i.e. the selected="selected" attribute is gone from the HTML.
Incidentally, the default values show up if I don't use embedded forms. The problem with avoiding embedded forms is that each form has identical inputs and therefore overwrites itself.
The action code is as such, some code omitted for brevity:
$serviceFormArray = array();
$this->fullForm = new ConfigForm();
foreach($this->serviceArray as $net => $service)
{
$this->partialForm = new ConfigForm();
foreach($service as $typeId => $val)
{
$typeObj = Doctrine::getTable('Type')->find($typeId);
$typeField = new sfWidgetFormChoice(array(
'default' => $val,
'choices' => array('1' => 'on', '0' => 'off'),
'label' => $typeObj->name)
);
$typeField->setDefault($val);
$serviceFormArray[$typeObj->name] = $typeField;
}
$netObj = Doctrine::getTable('Network')->find($net);
$this->partialForm->setWidgets($serviceFormArray);
$this->fullForm->embedForm($netObj->name,$this->partialForm);
}
and the template looks like this, some code omitted for brevity:
<div class="sectionBox">
<?php echo $fullForm->renderFormTag('/configure/submitconfig') ?>
<?php foreach ($fullForm->getVisibleFields() as $part => $field): ?>
<div class="settingsField">
<?php echo $field->renderLabel() ?>
<?php echo $field->render() ?>
<input type="hidden" name="plug" value="<?php echo $plugName; ?>"/>
</div>
<?php endforeach; ?>
<div id="submitConfig"><input type="submit" value="Save"/></div>
</form>
</div>
Try setting default value via $form->setDefault($name, $default).
$this->partialForm->setDefault($typeObj->name, $val);