Drupal 7 get node id in AJAX - drupal-7

i'm submitting a form to create node using ajax. I can able to create a node using drupal_get_form('node_form', $node) but i need the node id in response. Can anyone help me out to get the node id in ajax response after creating the node.

Or you can add the hidden field to the form like this:
$form['hidden-nid'] = array(
'#type' => 'hidden',
'#value' => menu_get_object()->nid,
);
and get the value in ajax function:
$id = intval($form_state['input']['hidden-nid']);

In the node_form function, do something like this,
$node = menu_get_object();
$node_id = $node->nid;
$form_state['#id'] = $node_id;
In the callback function you can get it as,
$id = $form_state['id'];

Related

CakePHP3 Render View to a Variable

I want to render the view to a variable without directly sending it to the browser. I used to do it with cakephp2.*. But, I cannot figure out how to do it in CakePHP3. Could you please tell me how to do it?
ViewBuilder was introduced in CakePHP 3.1 and handles the rendering of views. When ever I want to render to a variable I always go look at how send email works.
From a controller:
function index() {
// you can have view variables.
$data = 'A view variable';
// create a builder (hint: new ViewBuilder() constructor works too)
$builder = $this->viewBuilder();
// configure as needed
$builder->layout('default');
$builder->template('index');
$builder->helpers(['Html']);
// create a view instance
$view = $builder->build(compact('data'));
// render to a variable
$output = $view->render();
}
For Ajax request/response, I use this:
public function print(){
if ($this->request->is('ajax')) {
$data = $this->request->getData();
$builder = $this->viewBuilder()
->setTemplatePath('ControllerName')
->setTemplate('print');
->setLayout('ajax');
->enableAutoLayout(false);
$view = $builder->build(compact('data'));
$html = $view->render();
$res = ['html' => $html];
$this->set('response',$res);
$this->set("_serialize",'response');
}
}
And the print.ctp is under Template/ControllerName

Google App Engine Send Grid PHP attachment

I am trying to add attachments as shown on https://github.com/sendgrid/sendgrid-google-php. But its not working by this way. I think I tried every possible solution but cant make this work. Here is my code.
<?php
require 'SendGrid_loader.php';
// Connect to your SendGrid account
$sendgrid = new SendGrid\SendGrid('myusername', 'mypassword');
// Make a message object
$mail = new SendGrid\Mail();
// Mail arrayi
$emails = array("mailadress1#test.com","mailadress2#test.com");
$names = array("name1", "name2");
// Add recipients and other message details
$mail->setTos($emails)->
setFrom('testsender#test.com')->
setFromName('Test Sender')->
setReplyTo('testemail#test.com')->
setSubject('Test')->
addAttachment("test.jpg")->
addCategory("TEST-GONDERIM")->
addUniqueArgument("BASIN", "YEREL-BASIN")->
addSubstitution("%name%", $names)->
setText('TEXT BODY MESSAGE')->
setHtml('<strong>%name% MERHABA,</br>BODY MESSAGE</strong>');
// Use the Web API to send your message
$sendgrid->send($mail);
?>
I tried to put test.jpg file on the same folder with this php file. Also tried to add like gs://bucket_name/test.jpg but not working. Any ideas. Thanks in advance
Solved with using web api v2 Curl version like this
$fileName = 'filename.pdf';
$image_data = file_get_contents('gs://my-bucket/filename.pdf');
sending part
$params = array(
'api_user' => $user,
'api_key' => $pass,
'x-smtpapi' => json_encode($json_string),
'to' => 'email#yourdomain.com',
'subject' => 'your subject',
'html' => 'testing body',
'text' => 'testing body',
'from' => 'yourmail#yourdomain.com',
'files['.$fileName.']' => $image_data
);
$request = $url.'api/mail.send.json';

Inserting new row instead of Updating

I am trying to update a profile in the database without passing the profile id as a paramater and instead of updating I am adding new row. I tried to use the getLastInsertId() but it did not work.
public function editProfile(){
if (isset($this->data)){
$Client = $this->Client->find('first', array(
'fields' => array('email','username','first_name','surname','country','phone_prefix','phone'),
'conditions' => array(
'Client.email' => $this->request->query['email'],
'Client.client_type' => $this->request->query['client_type']
),
)
);
if($this->request->is('get')) {
if($data = $this->Client->save($this->request->query,array('first_name','surname','country','phone_prefix','phone')))
{
$this->Client->id = $this->Client->getLastInsertId();
It looks like you are trying to update a record in your Client model based on the email and client type because (I assume) you don't know the id.
Try changing your code to get the id based on the information you have-
public function editProfile(){
if($this->request->is('get')) {
if (isset($this->data)){
$conditions = array('conditions' => array(
'email' => $this->request->query['email'],
'client_type' => $this->request->query['client_type']
));
$this->Client->id = $this->Client->field('id', $conditions);
if($this->Client->save($this->request->query,array('id', 'first_name','surname','country','phone_prefix','phone')))
{
$this->setFlash('success');
}else{
$this->setFlash('fail');
}
}
}
Looking at the code it seems you have two possible keys:
The client email
The last saved id
First, using the last saved id seems very fragile - how can you be sure this will always be the record you want to update? Best to avoid this approach.
However, if you have the user's email you can use the following method:
$client = $this->Client->findByEmail($this->request->data['Client']['email']);
$id = $client['Client']['id'];
You now have the client record id available to use in your save. Something like:
$data = array();
$data['Client']['id'] = $id;
$data['Client']['fieldFromForm'] = $this->data['Client']['fieldFromForm'];
$this->Client->save($data);
...
Without the id, cake will assume that you are adding a new Client. To update via save you'll need to tell it which Client.id to update in some way. Is there some reason that you can't provide the Client.id? The usual approach is to have Client.id present in a hidden input on your edit view which you can then pass to the edit action...

Cakephp load element with BBcode/shortcode

I am looking for input/help on how to do this. Might be some PHP/cake developers could provide some good solutions here. Cakephp 2.3 something :)
Problem; How to put shortcodes in wysiwyg editor (example: [slideshow=1]slideshow here[/slideshow]) and render an element (in this case, loading and displaying the slideshow with ID=1).
ShortcodeHelper.php
App::import('Helper', 'Html', 'Router');
class ShortcodeHelper extends AppHelper {
public $shortcodes = array(
'slideshow' => '/(\[slideshow=)(.+?)(\])(.+?)(\[\/slideshow\])/'
);
public $returncodes = array(
//'slideshow' => $this->render('/elements/slideshow', array('id'=>'\\2'))
'slideshow' => '<strong rel="\\2">\\4</strong>'
);
public function render($content, $render=null) {
$shortcodes = $this->shortcodes;
$returncodes = $this->returncodes;
if(isset($render)) {
$temp_shortcodes = array();
$temp_returncodes = array();
foreach ($render as $key => $value) {
$temp_shortcodes[$key] = $shortcodes[$value];
$temp_returncodes[$key] = $returncodes[$value];
}
$returncodes = $temp_returncodes;
$shortcodes = $temp_shortcodes;
}
$return = preg_replace($shortcodes, $returncodes, $content);
return $this->output($return);
}
}
view.ctp (call render function from helper, and run the page-content trough it):
<?php echo $this->Shortcode->render($page['Page']['body']); ?>
Thanks. You are awesome!! :)
-Tom
You need to turn the short code string into a method call, parse it.
Your helper will need to be able to detect them and then break them up. Your code needs to be mapped somehow to a callback.
// [slideshow=1]slideshow here[/slideshow]
$this->requestAction(array('controller' => 'slideshows', 'action' => 'view', $id);
For example.
I think the best way here would be to just always map the first arg, the "function call" to an element instead and pass all other args to the element. This way you can do there whatever you want and request the data or just simply display HTML only.
I would put the mapping of short codes into something like Configure::write('ShortCodes', $shortCodeArray); this way plugins could even register their callback mapping by simply adding them to that array.
array(
'slideshow' => array('controller' => 'slideshows', 'action' => 'view')
);
You'll have to merge that with args from the parsed short code.
Why requestAction()? You should not violate the MVC pattern, for this reason you'll have to request the data via requestAction().

Drupal 7 webform submission to remote mysql database

When a user fills out a webform on my Drupal 7 site, on submitting, I need the submission data to be sent over to another database. I'm using hook_webform_submission_insert in a custom module, but I can only get the sid and nid to be inserted into the table. I need my webform fields to be sent also; like first_name, last_name, email, etc. But I get errors upon submitting.
<?php
function hook_webform_submission_insert($node, $submission) {
// Insert a record into a 3rd-party module table when a submission is added.
db_insert('mymodule_table')
->fields(array(
'nid' => $node->nid,
'sid' => $submission->sid,
'foo' => 'foo_data',
))
->execute();
}
?>
I've tried 'first_name' => 'first_name', but it doesn't work. What am I doing wrong?
To get all the submitted data you'll have to go about this a slightly different way. First add an additional submit handler to call a custom function in your module using form alter:
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
if($form_id == "YOUR_WEBFORM_ID") {
$form['#submit'][] = 'MYMODULE_additional_insert';
}
}
Then access the form data and process accordingly from your custom function.
function MYMODULE_additional_insert($form, &$form_state) {
$data = $form['submitted'];
// Insert a record into a 3rd-party module table when a submission is added.
db_insert('mymodule_table')
->fields(array(
'foo' => $data['FOO_FIELD']['#value'],
))
->execute();
}

Resources