I know that we can add edit and delete data in a table statically in Drupal. But is there any way we can add edit and delete data via clicking a link just near to each row so that on clicking "add " button should generate a new row, and on clicking edit should highlight all the contents of the row as fr editing and delete should remove the row. The basic table I created is this:
<?php
$header = array('Emp ID', 'Emp Name', 'Emp Age');
$rows = array();
$sql = 'SELECT empid, name, age FROM {employee} ORDER BY name';
$result = db_query($sql);
while ($row = db_fetch_array($result)) {
$rows[] = $row;
}
print theme('table', $header, $rows);
?>
You can build it. You've already got your Read mode, so you need a Create/Update/Delete... there is some help on the internet for basic CRUD modules. Very basically, the update part, (first having a menu hook using % wildcard which is what arg(1) will be:
function crud_module_edit_form() {
$result = db_select('employee', 'e')
->fields('e', array('empid', 'name'))
->condition('empid', arg(1), '=')
->orderBy('name', 'DESC')
->execute()
->fetch();
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('Name'),
'#default_value' => isset($result->name) ? $result->name : '',
'#required' => TRUE,
);
return $form;
}
Then the submit function for the above form to update the record. You could use db_merge here instead and then use the same page for both the Add and the Update functions.
function crud_app_edit_form_submit($form, &$form_state) {
db_update('employees')
->fields(array(
'name' => check_plain($form_state['values']['name']),
))
->condition('empid', arg(1), '=')
->execute();
drupal_set_message(t('Employee updated'));
}
Related
I have custom post types called "Products". and using the AFC(Advanced Custom Fields) plugin with this post type.
Below is what ACF has in fields group
- one filed called 'Product Description' as text area
- three text fields called 'Feature 1, Feature 2,Feature 3'
What I want to achieve is to get the data from external JSON file and populate the above ACF fields in the backend. I did some research and found Wordpress offers wp_remote_get() function to request the remote file. But I have no clue where to begin with to use this function or any other approach to use external JSON and populate these fields. Will really appreciate it someone points me to the right direction or any tutorial that shows how to achieve that. Thanks
I figured it out. View the working code below.
// Get JSON and Decode
$json_request = wp_remote_get( 'http://wp-test/test/data.json');
if( is_wp_error( $json_request ) ) {
return false;
}
$json_body = wp_remote_retrieve_body( $json_request );
$json_data = json_decode( $json_body );
// Create the new post and populate the fields
foreach( $json_data->products as $item ) {
$title = $item->title;
$desc = $item->content;
$status = $item->status;
$new_post = array(
'post_title' => $title,
'post_content' => $desc,
'post_status' => $status,
'post_author' => $userID,
'post_type' => 'products'
);
$post_id = post_exists( $title );
if (!$post_id) {
$post_id = wp_insert_post($new_post);
}
}
here is code of dropdownlist.. but when I select multiple values it gives validation error "task must be string"
how to save multiple values (array)?
<?php echo $form->field($model, 'task')->widget(Select2::classname(), [
'data' => $companiesList,
'options' => ['placeholder' => 'Select company...','multiple' => true],
'pluginOptions' => ['allowClear' => true,],
]);?>
how to give checkbox for each value in list?
you have to save multiple values in many-to-many tabels ,
after changing the rules to [['task'], 'safe'] from Mr Skull answer , you have to get all data like this :
foreach ( $model->task as $single_task){
$task = new _many_to_many_model();
$task->side_1_id = single_task;
$task->side_2_id = $model->id;
$task->save();
}
after this comment :
all selected value should go in single column
you don't need to use many-to-many !
I use "-" as delimiter,
$all_taskes = "";
foreach ( $model->task as $single_task){
$all_taskes .= single_task."-";
}
$model->task = all_taskes;
Hi there ,
$model->save();
foreach ($model->task as $cat) {
$m = new \common\models\_many_to_many_model();
$m->ads_id = $model->id; // change in to yorr base model ID and use it's put after $model->save
$m->category_id = $cat; // category_id is your many to many model filed id
$m->save();
}
I have several fields in my form that i wish to post to the database. All the other fields bar the dropdown field are all working fine
The official documentation for zend 2 is not really clear on how to deal with posting data from a dropdown menu into the database
Here's what i have:
my addAction in the controller
public function addAction()
{
$form = new UsersForm();
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost())
{
$users = new Users();
$form->setInputFilter($users->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid())
{
$users->exchangeArray($form->getData());
$this->getUsersTable()->saveUser($users);
// Redirect to list of albums
return $this->redirect()->toRoute('index');
}
}
return array('form' => $form);
}
my form
public function __construct($name = null)
{
// we want to ignore the name passed
parent::__construct('users');
//other form elements...
//the dropdown menu
$this->add(array(
'type' => 'Select',
'name' => 'groupid',
'options' => array(
'label' => 'Group',
'value_options' => array(
'0' => 'Not Selected',
'1' => 'Super Admin',
'2' => 'Company Admin',
),
),
));
//...
}
}
the view
<?php
$form->setAttribute('action', $this->url('user', array('action' => 'add')));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formRow($form->get('groupid'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
When i run my application for the addAction, i get an error message:
Statement could not be executed (23000 - 1048 - Column 'GroupID' cannot be null)
where 'GroupID' is the column in my table that takes the value from the dropdown which means the field is not being posted
I need help on this
If the column in your database is GroupID, the form element should also be named that. Yours is groupid (i.e. lowercase). If that doesn't fix the issue, please edit your question to include the DB structure and the code for the saveUser() function.
I need to insert multioptions to a dropdown list, options taken from a table from my database.
I created the elements like:
$this->add(array(
'name' => 'company',
'type' => 'Zend\Form\Element\Select',
//'multiOptions'=> $options,
'options' => array(
'label' => 'Company',
),
'attributes' => array(
'style' => "float:right;",
),
));
I want to choose from a dropdown list some values that are in a table in my database. For example I have the entity Contacts and I need to choose for the contact a company that is in a table named companies in the database.
After reading on zend framework's site, I tried using this code:
$params = array(
'driver'=>'Pdo_Mysql',
'host'=>'localhost',
'username'=>'root',
'password'=>'',
'dbname' =>'myDataBase'
);
$db = new \Zend\Db\Adapter\Adapter($params);
$sql= new Sql($db);
$select = $sql->select();
$select ->from('companies')
->columns(array('id','company_name'))
->order(" 'company_name' ASC");
I also read on some other sites that I could use a function:
$options = $sql->fetchPairs('SELECT id, name FROM country ORDER BY name ASC');
but it seems it doesn't exist anymore in Zend Framework 2.
Please guys, give me a hand. If the code isn't good and you have a better idea, please tell me.
Thanks in advance!
This is just a quick and dirty answer, but i guess it can get you started.
Create a ServiceFactory, this should be done in a separate factory class instead of a closure, but i still use a closure - faster to write ;)
Get the config from the ServiceLocator so you have access to the DB-Params
Create your default SQL Stuff to retriefe the value_options
Populate the value_options using the setValueOptions($valueOptions) function of your given form-element
Module.php getServiceConfig()
return array(
'factories' => array(
'my-form-factory' => function($serviceLocator) {
$form = new My\Form();
$config = $serviceLocator->get('config');
$db = new \Zend\Db\Auth\Adapter\Adapter($config['dbParams']); //or whatever you named the array key
$sql = //do your SQL Stuff
// This is a fake array, it should be your $sql result in the given format
$result = array('value' => 'label', 'value2' => 'label2');
$form->get('elementToPopulate')->setValueOptions($result);
return $form;
}
)
);
SomeController.php someAction()
$form = $this->getServiceLocator()->get('my-form-factory');
return new ViewModel(array(
'form' => $form
));
I hope this gets you started
you have to add that field validation on controller for setting value in it.
$select = $db->select()->where("state_code = ?",$arr["state_code"]);
$resultSet = $cityObj->fetchAll($select);
$cityArr = $resultSet->toArray();
$city_ar = array();
foreach($cityArr as $city){
$city_ar[$city['id']] = $city['company'];
}
$form->company->setMultiOptions($city_ar);
$form->company->setValue($val["company"]);
by using this code drop down of country have the value that are in resultset array ($resultSet).
I have a client project that has posts assigned to their country of origin.
The client wants to be able to search the posts by continent and or region.
I have a separate table that assigns each country to its respective region, and I have the WP query that uses the resulting array:
$country_names = array('England','France','Germany',...); // this would be the result from fetching countries associated with a region.
$args = array(
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'country',
'value' => $country_names,
'compare' => 'IN'
)
)
);
$query = new WP_Query( $args );
What I'm having trouble with is the part in the middle. Normally, I'd use some standard PHP/MySQL to craft the array:
<?php
//Process incoming variable
if(!empty($_REQUEST['region'])){
$region = $_REQUEST['region'];
} else {
$region = NULL;
}
// Make a MySQL Connection
$query = "SELECT * FROM regions WHERE region='$region'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['country'];
?>
However, I'm having trouble making it work within a WP template, since WP manages the incoming variables using its own internal functions.
Can anyone help me to connect the two together? I'm sure I'm overlooking some simple step here, or else I'm not using some built-in WP function.
Any help is appreciated.
Thanks!
ty
Add this in your functions.php
add_filter( 'query_vars', 'addnew_query_vars', 10, 1 );
function addnew_query_vars($vars)
{
$vars[] = 'region'; // region is the variable you want to add
$vars[] = 'anotherVar';
return $vars;
}
Then get it
$region=get_query_var('region')
Update
$regions = $wpdb->get_results("SELECT ".$region." FROM `".$wpdb->regions."`");
if($regions)
{
foreach($regions as $region)
{
// your code
}
}